using IcsSEMCtrl.Com.FieldBus;
using IcsSEMCtrl.Com.Secs;
using IcsSEMCtrl.Db;
using IcsSEMCtrl.Device;
using IcsSEMCtrl.Device.Observe;
using IcsSEMCtrl.Global;
using IcsSEMCtrl.Global.Com;
using IcsSEMCtrl.Global.Device;
using IcsSEMCtrl.Service.Alarm;
using IcsSEMCtrl.Service.Logger;
using IcsSEMCtrl.Service.Material;
using IcsSEMCtrl.Util;
using IcsSEMCtrl.Util.Client;
using Lifter.Com.Secom;
using Lifter.Device.Dispatcher;
using Lifter.Device.Service;
using Lifter.Device.Unit;
using Lifter.Event.Lifter;
using Lifter.Global;
using Lifter.Global.Device;
using Lifter.Gui.Monitor.Panels;
using Lifter.Utility;
using SEComEnabler.SEComStructure;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using TKT.Lifter.CIM.Lifter.Device.Service;
using TKT.Lifter.CIM.Lifter.Device.Unit;
using TKT.Lifter.CIM.Lifter.Event.Lifter;
using TKT.Lifter.CIM.Lifter.Global;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Popups;
using TKT.Lifter.CIM.Lifter.HSMSMsg.HSMSConstant;
using TKT.Lifter.CIM.Lifter.HSMSMsg.TransferActionMsg;
using static TKT.Lifter.CIM.Lifter.Global.SysTemConstant;

namespace Lifter.Device
{
    [HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
    public class LifterSEM : Equipment
    {
        private enum enumP2PState
        {
            NONE,
            COMMAND_SEND,
            RECEIVE_OK,
            RECEIVE_NG
        }
        /// <summary>
        /// 统计时间类型
        /// </summary>
        public enum statisticTimeType
        {
            TRANSFERTIME, //搬送时间
            SYSTEMNOALARMTIME //正常运行时间
        }
        private const string CLASS = "LifterSEM";
        public LifterDispatcher LDispatcher = null;
        public SecsCEID LHostReport = null;
        private enumTransferEndProcess transferEndProcess = enumTransferEndProcess.ON_UNLOADCOMPLETE;
        protected Dictionary<string, LocationUnit> LocationUnits = new Dictionary<string, LocationUnit>();
        public Dictionary<string, Vehicle> Vehicles = new Dictionary<string, Vehicle>(); //轿厢对象字典
        public Dictionary<string, LifterPort> LifterPorts = new Dictionary<string, LifterPort>();//Port对象字典
        private Dictionary<string, ConveyorBuffer> conveyorBuffers = new Dictionary<string, ConveyorBuffer>();// CV对象字典
        public Dictionary<string, EFUFan> EFUFans = new Dictionary<string, EFUFan>(); //风机对象字典
        protected List<LifterPort> lstLifterPorts = new List<LifterPort>();
        private string iD;
        private string hostID;
        private VehicleOperationMode vehicleOperationMode;
        private string maker;
        private string softwareVersion;
        private StartupCommunicationState startupCommunicationMode;
        private int waitInTimeoutLimit;
        private int conveyorTimeOutLimit;
        private int transferQueueDelayTime = 0;
        private int transferQueuePriorityUp = 0;
        private bool isTransferQueueDeleyUP = false;
        private enumTrackingLevel trackingLevel = enumTrackingLevel.NONE;
        private enumHostControlState hostControlState = enumHostControlState.SC_OFFLINE_HOST;
        public enumSCStateMode sCStatemode = enumSCStateMode.SC_PAUSED;//设备模式切换（/AUTO/PAUED/PAUSING）
        private bool isPLCConnected = false;
        private enumRIDState deviceState = enumRIDState.DOWN;
        private enumAIMDeviceState deviceStateForAim = enumAIMDeviceState.OutofService;
        public enumRIDState oldDDeviceState = enumRIDState.DOWN;
        public AbstractSecsDriver secsDriver = null;
        private bool userPrivilige = false;//用户是否有登录权限
        private string userName = "";//用户登录名
        private string userPower = "";
        private string languageType = "";
        private int loginTimeCount = 0;
        private string exceptionPortHostId = "";
        private bool isFirstScan = false;
        private short shuttlePostiion = 0;
        private int cvWaitInCountLimit = 0;
        private Timer mainTimer;
        private string LogMsg = "";
        public bool isReportPortBufferShift = true;
        public bool isHandClearCommand = false; //是否是手动清除命令flag，在记录时间的时候会用到
        private int pri;
        public List<EcpAlarm> reportAlarms = new List<EcpAlarm>();
        public static object alarmMonitor = new object();//操作报警List锁

        public DateTime transferStartTime; //搬送开始时间
        public DateTime transferEndTime; //搬送结束时间
        public DateTime systemNoAlarmStartTime; //设备正常运行开始时间
        public DateTime systemNoAlarmEndTime; //设备正常运行结束时间

        private statisticTimeType statisticTimeFlag; //记录当前时间统计类型
        private enumCimStatus cimStatus = enumCimStatus.OFF;//Cim状态
        private ShuttleMaster shuttleMaster = null;

        private int commandTimeoutCount; //指令超时时间设定
        public bool isWaitCVMaterialIsNull; //是否需要判断当前楼层入料CV为空时，直接做move动作
        public bool CimStatusChangeEnableFlag = false; //CIM状态是否能切换
        public enumTransferEndProcess TransferEndProcess
        {
            get
            {
                return this.transferEndProcess;
            }
        }
        public string HostID
        {
            get
            {
                return this.hostID;
            }
            set
            {
                this.hostID = value;
            }
        }
        public VehicleOperationMode VehicleOperationMode
        {
            get
            {
                return this.vehicleOperationMode;
            }
            set
            {
                this.vehicleOperationMode = value;
            }
        }
        public int WaitInTimeoutLimit
        {
            get
            {
                return this.waitInTimeoutLimit;
            }
            set
            {
                this.waitInTimeoutLimit = value;
            }
        }
        public int ConveyorTimeOutLimit
        {
            get
            {
                return this.conveyorTimeOutLimit;
            }
            set
            {
                this.conveyorTimeOutLimit = value;
            }
        }
        public int TransferQueueDelayTime
        {
            get
            {
                return this.transferQueueDelayTime;
            }
            set
            {
                this.transferQueueDelayTime = value;
            }
        }
        public int TransferQueuePriorityUp
        {
            get
            {
                return this.transferQueuePriorityUp;
            }
            set
            {
                this.transferQueuePriorityUp = value;
            }
        }
        public bool IsTransferQueueDeleyUP
        {
            get
            {
                return this.isTransferQueueDeleyUP;
            }
            set
            {
                this.isTransferQueueDeleyUP = value;
            }
        }
        public enumHostControlState HostControlState
        {
            get
            {
                return this.hostControlState;
            }
            set
            {
                this.hostControlState = value;
                this.HostControlStateChange();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public enumSCStateMode SCStatemode
        {
            get
            {
                return this.sCStatemode;
            }
            set
            {
                this.sCStatemode = value;
                this.DoChangeSCMode();
            }
        }
        public bool IsPLCConnected
        {
            get
            {
                return this.isPLCConnected;
            }
            set
            {
                this.isPLCConnected = value;
                this.OnCheckPLCConnect(value);
            }
        }
        public enumRIDState DeviceState
        {
            get
            {
                return this.deviceState;
            }
            set
            {
                oldDDeviceState = this.deviceState;
                this.deviceState = value;
                this.OnDeviceStateChange();
            }
        }
        /// <summary>
        /// 插入日统计表插入数据
        /// </summary>
        /// <param name="timeType">时间类型</param>
        public void AddDataStatisticByDay(statisticTimeType timeType)
        {
            DBConnection dBConnection = DBControl.GetConnection();
            string sqlString = "";
            switch (timeType)
            {
                case statisticTimeType.TRANSFERTIME:
                    {
                        TimeSpan intervalTime = this.transferEndTime - this.transferStartTime;
                        sqlString = string.Format("INSERT INTO DATASTATISTICBYDAY VALUES('{0}','{1}','{2}',{3},'{4}')", timeType.ToString(), this.transferStartTime, this.transferEndTime, Convert.ToInt32(intervalTime.TotalSeconds), DateTime.Now.ToString("yyyy-MM-dd"));
                        break;
                    }
                case statisticTimeType.SYSTEMNOALARMTIME:
                    {
                        TimeSpan intervalTime = this.systemNoAlarmEndTime - this.systemNoAlarmStartTime;
                        sqlString = string.Format("INSERT INTO DATASTATISTICBYDAY VALUES('{0}','{1}','{2}',{3},'{4}')", timeType.ToString(), this.systemNoAlarmStartTime, this.systemNoAlarmEndTime, Convert.ToInt32(intervalTime.TotalSeconds), DateTime.Now.ToString("yyyy-MM-dd"));
                        break;
                    }
            }
            try
            {
                int returnCode = dBConnection.ExecuteUpdate(sqlString);
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception ex)
            {
                PopupNotice.TipsPopups("统计时间警报内容:" + ex.Message, ex.Message);
            }
        }
        /// <summary>
        /// 统计时间跨天操作
        /// </summary>
        private void CrossDay()
        {
            this.TransferCrossDay();
            this.SystemNoAlarmCrossDay();
        }
        public void TransferCrossDay()
        {
            try
            {
                if (this.shuttleMaster.TransferStatus == ShuttleMaster.ShuttleTransferStatus.Move)
                {
                    DBConnection dBConnection = DBControl.GetConnection();
                    string sqlString = "";

                    this.transferEndTime = DateTime.Today.AddSeconds(-1);
                    TimeSpan transferIntervalTime = this.transferEndTime - this.transferStartTime;
                    sqlString = string.Format("INSERT INTO DATASTATISTICBYDAY VALUES('{0}','{1}','{2}',{3},'{4}')", statisticTimeFlag.ToString(), this.transferStartTime, this.transferEndTime, Convert.ToInt32(transferIntervalTime.TotalSeconds), DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
                    this.transferStartTime = DateTime.Today;

                    dBConnection.ExecuteUpdate(sqlString);
                    DBControl.RemoveDBConection(dBConnection);
                }
            }
            catch (Exception)
            {
            }
        }
        public void SystemNoAlarmCrossDay()
        {
            DBConnection dBConnection = DBControl.GetConnection();
            string sqlString = "";
            try
            {
                this.systemNoAlarmEndTime = DateTime.Today.AddSeconds(-1);
                TimeSpan systemIntervalTime = this.systemNoAlarmEndTime - this.systemNoAlarmStartTime;
                sqlString = string.Format("INSERT INTO DATASTATISTICBYDAY VALUES('{0}','{1}','{2}',{3},'{4}')", statisticTimeFlag.ToString(), this.systemNoAlarmStartTime, this.systemNoAlarmEndTime, Convert.ToInt32(systemIntervalTime.TotalSeconds), DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
                this.systemNoAlarmStartTime = DateTime.Today;

                dBConnection.ExecuteUpdate(sqlString);
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 添加一笔数据到DataStatistics表
        /// </summary>
        public void AddDataStatistics()
        {
            //执行跨天操作
            this.CrossDay();
            Thread.Sleep(5000);
            double utilizaTionRate = 0.00;
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();

                int transferQTY = this.GetTransferQTY(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));  //搬送数量

                int transferTime = this.GetStatisticTimeByDay(statisticTimeType.TRANSFERTIME, DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));//设备搬送时间（单位：秒）
                int systemNoAlarmTime = this.GetStatisticTimeByDay(statisticTimeType.SYSTEMNOALARMTIME, DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));//设备正常运行时间（单位：秒）

                if ((Convert.ToDouble(systemNoAlarmTime)) == 0)
                {
                    utilizaTionRate = 0.00;  //稼动率
                }
                else
                {
                    utilizaTionRate = (int)((Convert.ToDouble(transferTime) / (Convert.ToDouble(systemNoAlarmTime))) * 100) / 100.00;
                }
                string sqlString = string.Format("INSERT INTO DATASTATISTICS VALUES('{0}','{1}',{2},{3},{4},{5},{6},{7},{8},'{9}')", DateTime.Today.AddSeconds(-1), this.HostID, transferQTY, utilizaTionRate, 0, 0, 0, transferTime, systemNoAlarmTime, DateTime.Today.AddSeconds(-1).ToString("yyyy-MM-dd"));

                dBConnection.ExecuteUpdate(sqlString);
                DBControl.RemoveDBConection(dBConnection);
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 获取每天的搬送数量
        /// </summary>
        private int GetTransferQTY(string time)
        {
            int QTY = 0;
            DBConnection dBConnection = DBControl.GetConnection();
            string sqlString = $"SELECT COUNT(*) AS QTY FROM COMMANDHISTORY WHERE COMPLETETIME LIKE '{time}%' AND TRANSFERRERULT = '{enumTransferResult.SUCCESS}'";

            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                if (sqlDataReader["QTY"] == null || "".Equals(sqlDataReader["QTY"].ToString()))
                {
                    QTY = 0;
                }
                else
                {
                    QTY = (int)sqlDataReader["QTY"];
                }

            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return QTY;
        }
        /// <summary>
        /// 通过时间类型获取当天所有的时间
        /// </summary>
        /// <param name="timeType">统计时间类型</param>
        /// <param name="time">时间</param>
        private int GetStatisticTimeByDay(statisticTimeType timeType, string time)
        {
            int QTY = 0;
            DBConnection dBConnection = DBControl.GetConnection();
            string sqlString = string.Format("SELECT SUM(CONSUMETIME) AS QTY FROM DATASTATISTICBYDAY WHERE TIMETYPE = '{0}' AND DATATIME = '{1}'", timeType.ToString(), time);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                if (sqlDataReader["QTY"] == null || "".Equals(sqlDataReader["QTY"].ToString()))
                {
                    QTY = 0;
                }
                else
                {
                    QTY = (int)sqlDataReader["QTY"];
                }

            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return QTY;
        }
        public AbstractSecsDriver SecsDriver
        {
            get
            {
                return this.secsDriver;
            }
        }
        public bool UserPrivilige
        {
            get
            {
                return this.userPrivilige;
            }
            set
            {
                this.userPrivilige = value;
                MainTopPanel.LogInOutChage(value);
            }
        }
        public int LoginTimeCount
        {
            get
            {
                return this.loginTimeCount;
            }
            set
            {
                this.loginTimeCount = value;
            }
        }
        public string ExceptionPortHostId
        {
            get
            {
                return this.exceptionPortHostId;
            }
            set
            {
                this.exceptionPortHostId = value;
            }
        }
        public bool IsFirstScan
        {
            get
            {
                return this.isFirstScan;
            }
        }
        public short ShuttlePostiion
        {
            get
            {
                return this.shuttlePostiion;
            }
        }
        public int CvWaitInCountLimit
        {
            get
            {
                int result;
                if (this.cvWaitInCountLimit > 0)
                {
                    result = this.cvWaitInCountLimit;
                }
                else
                {
                    string userDefinedPropertyValue = base.GetUserDefinedPropertyValue("WAITIN_TIMEOUT", "20", false);
                    this.cvWaitInCountLimit = int.Parse(userDefinedPropertyValue);
                    result = this.cvWaitInCountLimit;
                }
                return result;
            }
        }
        /// <summary>
        /// CIM状态显示
        /// </summary>
        public Observable _I_CIMSTATUS
        {
            get
            {
                return base.Observables["CIMSTATUS"];
            }
        }
        /// <summary>
        /// CIM状态显示
        /// </summary>
        public Observable _I_CIMSTATUSCHANGEENABLE
        {
            get
            {
                return base.Observables["CIMSTATUSCHANGEENABLE"];
            }
        }
        public bool O_CIMSTATUSCHANGE
        {
            set
            {
                base.Observables["CIMSTATUSCHANGE"].AsBoolean = value;
            }
        }
        public short O_CIMSTATUSCHANGEVALUE
        {
            set
            {
                base.Observables["CIMSTATUSCHANGEVALUE"].AsShort = value;
            }
        }
        /// <summary>
        /// Cim状态
        /// </summary>
        public enumCimStatus CimStatus
        {
            get
            {
                return this.cimStatus;
            }
            set
            {
                this.cimStatus = value;
            }
        }
        public Observable _I_TRACTIONMACHINEPOWER
        {
            get
            {
                return base.Observables["TRACTIONMACHINEPOWER"];
            }
        }
        public Observable _I_TRACTIONMACHINEFREQUENCY
        {
            get
            {
                return base.Observables["TRACTIONMACHINEFREQUENCY"];
            }
        }
        public Observable _I_TRACTIONMACHINEHIGHSPEED
        {
            get
            {
                return base.Observables["TRACTIONMACHINEHIGHSPEED"];
            }
        }
        public Observable _I_TRACTIONMACHINEMEDIUMSPEED
        {
            get
            {
                return base.Observables["TRACTIONMACHINEMEDIUMSPEED"];
            }
        }

        public Observable _I_TRACTIONMACHINELOWSPEED
        {
            get
            {
                return base.Observables["TRACTIONMACHINELOWSPEED"];
            }
        }
        public Observable _I_SHUTTLECVPOWER
        {
            get
            {
                return base.Observables["SHUTTLECVPOWER"];
            }
        }
        public Observable _I_SHUTTLECVFREQUENCY
        {
            get
            {
                return base.Observables["SHUTTLECVFREQUENCY"];
            }
        }
        public Observable _I_AMMETER1APHASEVOLTAGE
        {
            get
            {
                return base.Observables["AMMETER1APHASEVOLTAGE"];
            }
        }
        public Observable _I_AMMETER1BPHASEVOLTAGE
        {
            get
            {
                return base.Observables["AMMETER1BPHASEVOLTAGE"];
            }
        }
        public Observable _I_AMMETER1CPHASEVOLTAGE
        {
            get
            {
                return base.Observables["AMMETER1CPHASEVOLTAGE"];
            }
        }

        public Observable _I_AMMETER1APHASECURRENT
        {
            get
            {
                return base.Observables["AMMETER1APHASECURRENT"];
            }
        }
        public Observable _I_AMMETER1BPHASECURRENT
        {
            get
            {
                return base.Observables["AMMETER1BPHASECURRENT"];
            }
        }
        public Observable _I_AMMETER1CPHASECURRENT
        {
            get
            {
                return base.Observables["AMMETER1CPHASECURRENT"];
            }
        }
        public Observable _I_AMMETER1FREQUENCY
        {
            get
            {
                return base.Observables["AMMETER1FREQUENCY"];
            }
        }
        public Observable _I_AMMETER2APHASEVOLTAGE
        {
            get
            {
                return base.Observables["AMMETER2APHASEVOLTAGE"];
            }
        }
        public Observable _I_AMMETER2BPHASEVOLTAGE
        {
            get
            {
                return base.Observables["AMMETER2BPHASEVOLTAGE"];
            }
        }
        public Observable _I_AMMETER2CPHASEVOLTAGE
        {
            get
            {
                return base.Observables["AMMETER2CPHASEVOLTAGE"];
            }
        }
        public Observable _I_AMMETER2APHASECURRENT
        {
            get
            {
                return base.Observables["AMMETER2APHASECURRENT"];
            }
        }
        public Observable _I_AMMETER2BPHASECURRENT
        {
            get
            {
                return base.Observables["AMMETER2BPHASECURRENT"];
            }
        }
        public Observable _I_AMMETER2CPHASECURRENT
        {
            get
            {
                return base.Observables["AMMETER2CPHASECURRENT"];
            }
        }
        public Observable _I_AMMETER2FREQUENCY
        {
            get
            {
                return base.Observables["AMMETER2FREQUENCY"];
            }
        }
        public Observable _I_1FCVPOWER
        {
            get
            {
                return base.Observables["1FCVPOWER"];
            }
        }
        public Observable _I_2FCVPOWER
        {
            get
            {
                return base.Observables["2FCVPOWER"];
            }
        }
        public Observable _I_3FCVPOWER
        {
            get
            {
                return base.Observables["3FCVPOWER"];
            }
        }
        public Observable _I_4FCVPOWER
        {
            get
            {
                return base.Observables["4FCVPOWER"];
            }
        }
        public Observable _I_PRESSURE
        {
            get
            {
                return base.Observables["PRESSURE"];
            }
        }
        public Observable _I_TEMPERATURE
        {
            get
            {
                return base.Observables["TEMPERATURE"];
            }
        }
        //设备暂停请求
        public bool O_PAUSEREQ
        {
            set
            {
                base.Observables["PAUSEREQ"].AsBoolean = value;
            }
        }
        //设备暂停请求回复
        public Observable _I_PAUSERPY
        {
            get
            {
                return base.Observables["PAUSERPY"];
            }
        }
        //设备复位请求
        public bool O_RESUMEREQ
        {
            set
            {
                base.Observables["RESUMEREQ"].AsBoolean = value;
            }
        }
        //设备复位请求回复
        public Observable _I_RESUMERPY
        {
            get
            {
                return base.Observables["RESUMERPY"];
            }
        }
        public short O_YEARDATASET
        {
            set
            {
                base.Observables["YEARDATASET"].AsShort = value;
            }
        }
        public short O_MONTHDATASET
        {
            set
            {
                base.Observables["MONTHDATASET"].AsShort = value;
            }
        }
        public short O_JudgeBoxOperation
        {
            set
            {
                base.Observables["JUDGEBOXOPERATION"].AsShort = value;
            }
        }
        public short O_DAYDATASET
        {
            set
            {
                base.Observables["DAYDATASET"].AsShort = value;
            }
        }
        public short O_TIMESETDATAHH
        {
            set
            {
                base.Observables["TIMESETDATAHH"].AsShort = value;
            }
        }
        public short O_TIMESETDATAMM
        {
            set
            {
                base.Observables["TIMESETDATAMM"].AsShort = value;
            }
        }
        public short O_TIMESETDATASS
        {
            set
            {
                base.Observables["TIMESETDATASS"].AsShort = value;
            }
        }
        public bool O_TIMESETREQ
        {
            set
            {
                base.Observables["TIMESETREQ"].AsBoolean = value;
            }
        }
        public bool O_P2P_COMMAND_SEND
        {
            set
            {
                base.Observables["P2P_COMMAND_SEND"].AsBoolean = value;
            }
        }
        public bool O_P2P_RECEIVE_OK_ACK
        {
            set
            {
                base.Observables["P2P_RECEIVE_OK_ACK"].AsBoolean = value;
            }
        }
        public bool O_P2P_RECEIVE_NG_ACK
        {
            set
            {
                base.Observables["P2P_RECEIVE_NG_ACK"].AsBoolean = value;
            }
        }
        public short O_P2P_FROM
        {
            set
            {
                base.Observables["P2P_FROM"].AsShort = value;
            }
        }
        public short O_P2P_TO
        {
            set
            {
                base.Observables["P2P_TO"].AsShort = value;
            }
        }
        //报警上报
        public Observable _I_ALARMREPORT
        {
            get
            {
                return base.Observables["ALARMREPORT"];
            }
        }
        //报警上报回复
        public bool O_ALARMREPORTRPY
        {
            set
            {
                base.Observables["ALARMREPORTRPY"].AsBoolean = value;
            }
        }
        //PLC报警复位上报
        public Observable _I_ALARMRESETREPORT
        {
            get
            {
                return base.Observables["ALARMRESETREPORT"];
            }
        }
        //PLC报警复位上报回复
        public bool O_ALARMRESETREPORTRPY
        {
            set
            {
                base.Observables["ALARMRESETREPORTRPY"].AsBoolean = value;
            }
        }
        //报警复位请求回复
        public Observable _I_ALARMRESETREQRPY
        {
            get
            {
                return base.Observables["ALARMRESETREQRPY"];
            }
        }
        //报警复位请求
        public bool O_ALARMRESETREQ
        {
            set
            {
                base.Observables["ALARMRESETREQ"].AsBoolean = value;
            }
        }
        public short I_ALARMCODE
        {
            get
            {
                return base.Observables["ALARMCODE"].AsShort;
            }
        }
        public string UserPower { get => userPower; set => userPower = value; }
        public string LanguageType { get => languageType; set => languageType = value; }
        public List<EcpAlarm> ReportAlarms { get => reportAlarms; set => reportAlarms = value; }
        internal ShuttleMaster ShuttleMaster { get => shuttleMaster; set => shuttleMaster = value; }
        public Dictionary<string, ConveyorBuffer> ConveyorBuffers { get => conveyorBuffers; set => conveyorBuffers = value; }
        public string UserName { get => userName; set => userName = value; }
        public int CommandTimeoutCount { get => commandTimeoutCount; set => commandTimeoutCount = value; }

        public LifterSEM()
        {
        }
        public LifterSEM(string lifterId, string hostID, VehicleOperationMode vehicleOperationMode, string maker, StartupCommunicationState plcCommunicationMode, int waitInTimeoutLimit, int conveyorTimeOutLimit, int transferQueueDelayTime, int transferQueuePriorityUp, bool isTransferQueueDeleyUP)
        {
            this.iD = lifterId;
            this.hostID = hostID;
            this.vehicleOperationMode = vehicleOperationMode;
            this.maker = maker;
            this.startupCommunicationMode = plcCommunicationMode;
            this.waitInTimeoutLimit = waitInTimeoutLimit;
            this.conveyorTimeOutLimit = conveyorTimeOutLimit;
            this.transferQueueDelayTime = transferQueueDelayTime;
            this.transferQueuePriorityUp = transferQueuePriorityUp;
            this.isTransferQueueDeleyUP = isTransferQueueDeleyUP;
        }
        public override void Init()
        {
            base.Init();
            if (this.LDispatcher == null)
            {
                this.LDispatcher = new LifterDispatcher(this);
            }
            foreach (LifterPort current in this.LifterPorts.Values)
            {
                this.lstLifterPorts.Add(current);
            }
            LifterPortComparer comparer = new LifterPortComparer();
            this.lstLifterPorts.Sort(comparer);
            this.LHostReport = new SecsCEID();
            this.AddSubscribe();
            MainTimerCallBack @object = new MainTimerCallBack();
            TimerCallback callback = new TimerCallback(@object.TimeCall);
            this.mainTimer = new Timer(callback, this, -1, 1000);
            this.softwareVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            try
            {
                CommandTimeoutCount = Convert.ToInt32(base.GetUserDefinedPropertyValue("CommandTimeOutCount", "20", false));
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在LifterSEM的Init方法中报错", ex);
            }
            this.LoadEQProperty();
        }
        public void LoadEQProperty()
        {
            this.isWaitCVMaterialIsNull = "T".Equals(base.GetUserDefinedPropertyValue("IS_WAITCV_ISNULL", "T", false));
        }
        public override void Startup()
        {
            base.Startup();
            this.LDispatcher.Start();
            if (this.secsDriver != null)
            {
                this.secsDriver.Close();
            }
            //创建sece协议驱动
            this.secsDriver = new SecomDriver();
            SecomDriver driv = this.secsDriver as SecomDriver;
            //初始化Tibco协议驱动
            /*            this.secsDriver = new TibcoRvComDriver();
                        TibcoRvComDriver driv = this.secsDriver as TibcoRvComDriver;
                        driv.OnRecvMessageLog += driv_OnRecvMessageLog;
                        driv.OnSendMessageLog += driv_OnSendMessageLog;*/
            this.secsDriver.Initialize("LFTC", null);
            this.SecsDriverEventDelegate();
            this.DoDBCompact();
            this.StartTimer();
        }
        public override void Shutdown()
        {
            this.StopTimer();
            if (this.LDispatcher != null)
            {
                this.LDispatcher.Stop();
            }
            base.Shutdown();
        }
        public void DoDBCompact()
        {
            base.DbCompact();
            LogHelper.loggerInfo("LIFTER DB COMPACTION COMPLETED");
        }
        public void DoReconcile()
        {
            this.isFirstScan = true;
            base.StartFirstScanObservables();
            this.isFirstScan = false;
            //base.StartScanObservables();
        }
        protected override int Add(DBConnection theDB)
        {
            int result = 0;
            try
            {
                base.Add(theDB);
                PreparedSqlParameter preparedSqlParameter = theDB.GetPreparedSqlParameter();
                preparedSqlParameter.SetVarChar("ID", this.iD);
                SqlDataReader sqlDataReader = theDB.ExecuteQuery("select * from LIFTER where ID =@ID", preparedSqlParameter);
                if (sqlDataReader.Read())
                {
                    LogHelper.loggerInfo("LifterSEM.add[" + this.iD + "]already Exist");
                }
                else
                {
                    PreparedSqlParameter preparedSqlParameter2 = theDB.GetPreparedSqlParameter();
                    preparedSqlParameter2.SetVarChar("ID", this.iD);
                    preparedSqlParameter2.SetVarChar("HOSTID", this.hostID);
                    preparedSqlParameter2.SetVarChar("VEHICLEOPERATIONMODE", VehicleOperationMode.ValueToString(this.vehicleOperationMode));
                    preparedSqlParameter2.SetVarChar("MAKER", this.maker);
                    preparedSqlParameter2.SetVarChar("PLCCOMMUNICATIONSTATE", StartupCommunicationState.ValueToString(this.startupCommunicationMode));
                    preparedSqlParameter2.SetInt("WAITINTIMEOUTLIMIT", this.waitInTimeoutLimit);
                    preparedSqlParameter2.SetInt("CONVEYORTIMEOUTLIMIT", this.conveyorTimeOutLimit);
                    preparedSqlParameter2.SetInt("TRANSFERQUEUEDELAYTIME", this.transferQueueDelayTime);
                    preparedSqlParameter2.SetInt("TRANSFERQUEUEPRIORITYUP", this.transferQueuePriorityUp);
                    preparedSqlParameter2.SetVarChar("ISTRANSFERQUEUEDELEYUP", this.isTransferQueueDeleyUP ? "T" : "F");
                    result = theDB.ExecuteUpdate("insert into LIFTER (ID,HOSTID,VEHICLEOPERATIONMODE,MAKER, PLCCOMMUNICATIONSTATE,WAITINTIMEOUTLIMIT, CONVEYORTIMEOUTLIMIT, TRANSFERQUEUEDELAYTIME,TRANSFERQUEUEPRIORITYUP ) values (@ID,@HOSTID,@VEHICLEOPERATIONMODE,@MAKER,@PLCCOMMUNICATIONSTATE,@WAITINTIMEOUTLIMIT,@CONVEYORTIMEOUTLIMIT,@TRANSFERQUEUEDELAYTIME,@TRANSFERQUEUEPRIORITYUP,@ISTRANSFERQUEUEDELEYUP)", preparedSqlParameter2);
                }
            }
            catch (SqlException ex)
            {
                LogHelper.loggerError("LifterSEM.add流程报错",ex);
                throw ex;
            }
            return result;
        }
        protected override void Load(DBConnection theDB)
        {
            try
            {
                base.Load(theDB);
                PreparedSqlParameter preparedSqlParameter = theDB.GetPreparedSqlParameter();
                preparedSqlParameter.SetVarChar("ID", this.elementId);
                SqlDataReader sqlDataReader = theDB.ExecuteQuery("select * from LIFTER where ID =@ID", preparedSqlParameter);
                if (sqlDataReader.Read())
                {
                    this.iD = (string)sqlDataReader["ID"];
                    this.hostID = (string)sqlDataReader["HOSTID"];
                    this.vehicleOperationMode = VehicleOperationMode.StringToValue((string)sqlDataReader["VEHICLEOPERATIONMODE"]);
                    this.maker = (string)sqlDataReader["MAKER"];
                    this.startupCommunicationMode = StartupCommunicationState.StringToValue((string)sqlDataReader["PLCCOMMUNICATIONSTATE"]);
                    this.waitInTimeoutLimit = (int)sqlDataReader["WAITINTIMEOUTLIMIT"];
                    this.conveyorTimeOutLimit = (int)sqlDataReader["CONVEYORTIMEOUTLIMIT"];
                    this.transferQueueDelayTime = (int)sqlDataReader["TRANSFERQUEUEDELAYTIME"];
                    this.transferQueuePriorityUp = (int)sqlDataReader["TRANSFERQUEUEPRIORITYUP"];
                    this.isTransferQueueDeleyUP = ((string)sqlDataReader["ISTRANSFERQUEUEDELEYUP"]).Equals("T");
                    this.VehicleLoad(); //加载轿厢，初始化轿厢对象
                    this.LifterPortLoad(); //加载Port，初始化Port对象
                    this.ConveyorBufferLoad(); //加载CV，初始化CV对象
                    this.EFUFansLoad();//加载风机，初始化风机对象
                }
                else
                {
                }
            }
            catch (SqlException ex)
            {
            }
            finally
            {
            }
        }
        protected override int Save(DBConnection theDB)
        {
            int result = 0;
            try
            {
                base.Save(theDB);
                if (base.DirtyFlag)
                {
                    base.DirtyFlag = false;
                    string sqlstring = string.Concat(new string[]
                    {
                        "HOSTID='",
                        this.hostID,
                        "',VEHICLEOPERATIONMODE='",
                        VehicleOperationMode.ValueToString(this.vehicleOperationMode),
                        "',MAKER='",
                        this.maker,
                        "',PLCCOMMUNICATIONSTATE='",
                        StartupCommunicationState.ValueToString(this.startupCommunicationMode),
                        "',WAITINTIMEOUTLIMIT='",
                        this.waitInTimeoutLimit.ToString(),
                        "', CONVEYORTIMEOUTLIMIT='",
                        this.conveyorTimeOutLimit.ToString(),
                        "', TRANSFERQUEUEDELAYTIME='",
                        this.transferQueueDelayTime.ToString(),
                        "', TRANSFERQUEUEPRIORITYUP='",
                        this.transferQueuePriorityUp.ToString(),
                        "', ISTRANSFERQUEUEDELEYUP='",
                        this.isTransferQueueDeleyUP ? "T" : "F",
                        "' Where ID='",
                        this.iD,
                        "'"
                    });
                    result = theDB.ExecuteUpdate(sqlstring);
                }
            }
            catch (SqlException ex)
            {
                LogHelper.loggerError("LifterSEM.Save发生错误",ex);
            }
            return result;
        }
        public void VehicleLoad()
        {
            foreach (string current in this.subsystems.Keys)
            {
                SubSystem subSystem = this.subsystems[current];
                //加载所有的轿厢，存入轿厢集合
                if (subSystem.SubSystemType == SubSystemType.VEHICLE)
                {
                    Vehicle vehicle = (Vehicle)subSystem;
                    vehicle.HostID = this.hostID + vehicle.HostID;
                    this.Vehicles.Add(current, vehicle);
                    LocationUnit locationUnit = (LocationUnit)subSystem;
                    locationUnit.HostID = vehicle.HostID;
                    this.LocationUnits.Add(current, locationUnit);
                }
                //加载轿厢Master对象
                if (subSystem.SubSystemType == SubSystemType.SHUTTLEMASTER)
                {
                    this.shuttleMaster = (ShuttleMaster)subSystem;
                    this.shuttleMaster.HostID = this.hostID + this.shuttleMaster.HostID;
                }
            }
        }
        /// <summary>
        /// 把subsystems集合里面初始化好的Port存放到LifterPorts集合中
        /// </summary>
        public void LifterPortLoad()
        {
            foreach (string current in this.subsystems.Keys)
            {
                SubSystem subSystem = this.subsystems[current];
                if (subSystem.SubSystemType == SubSystemType.LIFTERPORT)
                {
                    LifterPort lifterPort = (LifterPort)subSystem;
                    lifterPort.HostID = this.HostID + lifterPort.HostID;
                    this.LifterPorts.Add(current, lifterPort);
                    LocationUnit locationUnit = (LocationUnit)subSystem;
                    locationUnit.HostID = lifterPort.HostID;
                    this.LocationUnits.Add(current, locationUnit);
                }
            }
        }
        /// <summary>
        /// 根据加载CV对象，将CV对象存放到 CV字典
        /// </summary>
        public void ConveyorBufferLoad()
        {
            foreach (string current in this.subsystems.Keys)
            {
                SubSystem subSystem = this.subsystems[current];
                if (subSystem.SubSystemType == SubSystemType.CONVEYORBUFFER)
                {
                    ConveyorBuffer conveyorBuffer = (ConveyorBuffer)subSystem;
                    conveyorBuffer.HostID = this.HostID + conveyorBuffer.HostID;
                    this.ConveyorBuffers.Add(current, conveyorBuffer);
                    LocationUnit locationUnit = (LocationUnit)subSystem;
                    locationUnit.HostID = conveyorBuffer.HostID;
                    this.LocationUnits.Add(current, locationUnit);
                }
            }
        }
        /// <summary>
        ///  加载风机对象，将风机对象存放到 EFUFan字典
        /// </summary>
        public void EFUFansLoad()
        {
            foreach (string current in this.subsystems.Keys)
            {
                SubSystem subSystem = this.subsystems[current];
                if (subSystem.SubSystemType == SubSystemType.EFUFAN)
                {
                    this.EFUFans.Add(current, (EFUFan)subSystem);
                }
            }
        }
        public Vehicle GetVehicle(string vehicleId)
        {
            Vehicle result;
            if (string.IsNullOrEmpty(vehicleId))
            {
                result = null;
            }
            else
            {
                Vehicle vehicle = null;
                if (this.Vehicles.ContainsKey(vehicleId))
                {
                    vehicle = this.Vehicles[vehicleId];
                }
                else
                {
                    foreach (Vehicle current in this.Vehicles.Values)
                    {
                        if (current.HostID == vehicleId || current.PlcID == vehicleId)
                        {
                            result = current;
                            return result;
                        }
                    }
                }
                result = vehicle;
            }
            return result;
        }
        public LifterPort GetLifterPort(string lifterPort)
        {
            LifterPort result;
            string lifterPortId = lifterPort.Trim();
            if (this.LifterPorts.ContainsKey(lifterPortId))
            {
                result = this.LifterPorts[lifterPortId];
            }
            else
            {
                foreach (LifterPort current in this.LifterPorts.Values)
                {
                    if (current.HostID.Trim() == lifterPortId || current.PlcID == lifterPortId)
                    {
                        result = current;
                        return result;
                    }
                }
                result = null;
            }
            return result;
        }
        public Dictionary<string, Vehicle> GetVehicleAll()
        {
            return this.Vehicles;
        }
        public Dictionary<string, LifterPort> GetLifterPortAll()
        {
            return this.LifterPorts;
        }
        public ConveyorBuffer GetConveyorBuffer(string bufferID)
        {
            ConveyorBuffer result;
            if (this.ConveyorBuffers.ContainsKey(bufferID))
            {
                result = this.ConveyorBuffers[bufferID];
            }
            else
            {
                foreach (ConveyorBuffer current in this.ConveyorBuffers.Values)
                {
                    if (current.HostID == bufferID || current.PlcID == bufferID)
                    {
                        result = current;
                        return result;
                    }
                }
                result = null;
            }
            return result;
        }
        public void AddSubscribe()
        {
            foreach (int current in this.fbdrivers.Keys)
            {
                if (this.fbdrivers[current].UseFlag)
                {
                    this.fbdrivers[current].ConnectionStateChanged += new delegateDriverConnectionStateChanged(this.LifterSEM_ConnectionStateChanged);
                    this.fbdrivers[current].ErrorOccurred += new delegateDriverErrorOccurred(this.LifterSEM_ErrorOccurred);
                }
            }

            this._I_TRACTIONMACHINEPOWER.ObservableValueChanged += new DelegateObservableValueChanged(this._I_TRACTIONMACHINEPOWER_ObservableValueChanged);
            this._I_TRACTIONMACHINEFREQUENCY.ObservableValueChanged += new DelegateObservableValueChanged(this._I_TRACTIONMACHINEFREQUENCY_ObservableValueChanged);
            this._I_TRACTIONMACHINEHIGHSPEED.ObservableValueChanged += new DelegateObservableValueChanged(this._I_TRACTIONMACHINEHIGHSPEED_ObservableValueChanged);
            this._I_TRACTIONMACHINEMEDIUMSPEED.ObservableValueChanged += new DelegateObservableValueChanged(this._I_TRACTIONMACHINEMEDIUMSPEED_ObservableValueChanged);
            this._I_TRACTIONMACHINELOWSPEED.ObservableValueChanged += new DelegateObservableValueChanged(_I_TRACTIONMACHINELOWSPEED_ObservableValueChanged);
            this._I_SHUTTLECVPOWER.ObservableValueChanged += new DelegateObservableValueChanged(this._I_SHUTTLECVPOWER_ObservableValueChanged);
            this._I_SHUTTLECVFREQUENCY.ObservableValueChanged += new DelegateObservableValueChanged(this._I_SHUTTLECVFREQUENCY_ObservableValueChanged);
            this._I_AMMETER1APHASEVOLTAGE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER1APHASEVOLTAGE_ObservableValueChanged);
            this._I_AMMETER1BPHASEVOLTAGE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER1BPHASEVOLTAGE_ObservableValueChanged);
            this._I_AMMETER1CPHASEVOLTAGE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER1CPHASEVOLTAGE_ObservableValueChanged);
            this._I_AMMETER1APHASECURRENT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER1APHASECURRENT_ObservableValueChanged);
            this._I_AMMETER1BPHASECURRENT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER1BPHASECURRENT_ObservableValueChanged);
            this._I_AMMETER1CPHASECURRENT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER1CPHASECURRENT_ObservableValueChanged);
            this._I_AMMETER1FREQUENCY.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER1FREQUENCY_ObservableValueChanged);
            this._I_AMMETER2APHASEVOLTAGE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER2APHASEVOLTAGE_ObservableValueChanged);
            this._I_AMMETER2BPHASEVOLTAGE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER2BPHASEVOLTAGE_ObservableValueChanged);
            this._I_AMMETER2CPHASEVOLTAGE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER2CPHASEVOLTAGE_ObservableValueChanged);
            this._I_AMMETER2APHASECURRENT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER2APHASECURRENT_ObservableValueChanged);
            this._I_AMMETER2BPHASECURRENT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER2BPHASECURRENT_ObservableValueChanged);
            this._I_AMMETER2CPHASECURRENT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER2CPHASECURRENT_ObservableValueChanged);
            this._I_AMMETER2FREQUENCY.ObservableValueChanged += new DelegateObservableValueChanged(this._I_AMMETER2FREQUENCY_ObservableValueChanged);
            this._I_1FCVPOWER.ObservableValueChanged += new DelegateObservableValueChanged(this._I_1FCVPOWER_ObservableValueChanged); ;
            this._I_2FCVPOWER.ObservableValueChanged += new DelegateObservableValueChanged(this._I_2FCVPOWER_ObservableValueChanged);
            this._I_3FCVPOWER.ObservableValueChanged += new DelegateObservableValueChanged(this._I_3FCVPOWER_ObservableValueChanged);
            this._I_4FCVPOWER.ObservableValueChanged += new DelegateObservableValueChanged(this._I_4FCVPOWER_ObservableValueChanged);
            this._I_PRESSURE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_PRESSURE_ObservableValueChanged);
            this._I_TEMPERATURE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_TEMPERATURE_ObservableValueChanged);

            //this._I_CDALFTMTOTORQUE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_CDALFTMTOTORQUE_ObservableValueChanged);
            this._I_CIMSTATUS.ObservableValueChanged += new DelegateObservableValueChanged(this._I_CIMSTATUS_ObservableValueChanged);
            this._I_CIMSTATUSCHANGEENABLE.ObservableValueChanged += new DelegateObservableValueChanged(this._I_CIMSTATUSCHANGEENABLE_ObservableValueChanged);
            this._I_ALARMREPORT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_ALARMREPORT_ObservableValueChanged);
            this._I_ALARMRESETREPORT.ObservableValueChanged += new DelegateObservableValueChanged(this._I_ALARMRESETREPORT_ObservableValueChanged);
            this._I_ALARMRESETREQRPY.ObservableValueChanged += new DelegateObservableValueChanged(this._I_ALARMRESETREQRPY_ObservableValueChanged);
            this._I_RESUMERPY.ObservableValueChanged += new DelegateObservableValueChanged(this._I_RESUMERPY_ObservableValueChanged);
            this._I_PAUSERPY.ObservableValueChanged += new DelegateObservableValueChanged(this._I_PAUSERPY_ObservableValueChanged);

/*            foreach (string current2 in base.Observables.Keys)
            {
                base.Observables[current2].ObservableLogEvent += new delegateObservableLogEvent(this.Lifter_ObservableLogEvent);
            }*/
        }

        private void _I_CIMSTATUSCHANGEENABLE_ObservableValueChanged(object sender, object value)
        {
            if ((bool)value)
            {
                this.CimStatusChangeEnableFlag = true;
            }
            else
            {
                this.CimStatusChangeEnableFlag = false;
            }
        }

        private void _I_TEMPERATURE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "TEMPERATURE",(short)value));
        }

        private void _I_PRESSURE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "PRESSURE", (short)value));
        }

        private void _I_4FCVPOWER_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "tb4FCVPOWER", (short)value));
        }

        private void _I_3FCVPOWER_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "tb3FCVPOWER", (short)value));
        }

        private void _I_2FCVPOWER_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "tb2FCVPOWER", (short)value));
        }

        private void _I_1FCVPOWER_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "tb1FCVPOWER", (short)value));
        }

        private void _I_AMMETER2FREQUENCY_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER2FREQUENCY", (short)value));
        }

        private void _I_AMMETER2CPHASECURRENT_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER2CPHASECURRENT", (short)value));
        }

        private void _I_AMMETER2BPHASECURRENT_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER2BPHASECURRENT", (short)value));
        }

        private void _I_AMMETER2APHASECURRENT_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER2APHASECURRENT", (short)value));
        }

        private void _I_AMMETER2CPHASEVOLTAGE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER2CPHASEVOLTAGE", (short)value));
        }

        private void _I_AMMETER2BPHASEVOLTAGE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER2BPHASEVOLTAGE", (short)value));
        }

        private void _I_AMMETER2APHASEVOLTAGE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER2APHASEVOLTAGE", (short)value));
        }

        private void _I_AMMETER1FREQUENCY_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER1FREQUENCY", (short)value));
        }

        private void _I_AMMETER1CPHASECURRENT_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER1CPHASECURRENT", (short)value));
        }

        private void _I_AMMETER1BPHASECURRENT_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER1BPHASECURRENT", (short)value));
        }

        private void _I_AMMETER1APHASECURRENT_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER1APHASECURRENT", (short)value));
        }

        private void _I_AMMETER1CPHASEVOLTAGE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER1CPHASEVOLTAGE", (short)value));
        }

        private void _I_AMMETER1BPHASEVOLTAGE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER1BPHASEVOLTAGE", (short)value));
        }

        private void _I_AMMETER1APHASEVOLTAGE_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "AMMETER1APHASEVOLTAGE", (short)value));
        }

        private void _I_SHUTTLECVFREQUENCY_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "SHUTTLECVFREQUENCY", (short)value));
        }

        private void _I_SHUTTLECVPOWER_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "SHUTTLECVPOWER", (short)value));
        }

        private void _I_TRACTIONMACHINELOWSPEED_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "TRACTIONMACHINELOWSPEED", (short)value));
        }

        private void _I_TRACTIONMACHINEMEDIUMSPEED_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "TRACTIONMACHINEMEDIUMSPEED", (short)value));
        }

        private void _I_TRACTIONMACHINEHIGHSPEED_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "TRACTIONMACHINEHIGHSPEED", (short)value));
        }

        private void _I_TRACTIONMACHINEFREQUENCY_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "TRACTIONMACHINEFREQUENCY", (short)value));
        }

        private void _I_TRACTIONMACHINEPOWER_ObservableValueChanged(object sender, object value)
        {
            base.PublishEvent(CDADataDisplayEvent.FormSubject("*"), new CDADataDisplayEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), "TRACTIONMACHINEPOWER", (short)value));
        }

        private void LifterSEM_ErrorOccurred(AbstractFieldBusDriver driver, int iErrorCode)
        {
            LogHelper.loggerInfo("PLC Driver Error Set, Error Code:" + iErrorCode);
        }
        private void LifterSEM_ConnectionStateChanged(AbstractFieldBusDriver driver, FBConnectionState connectionState)
        {
            if (connectionState == FBConnectionState.CONNECTED)
            {
                this.isPLCConnected = true;
            }
            else
            {
                this.isPLCConnected = false;
            }
            base.PublishEvent(LifterPLCConnectionEvent.FormSubject("*"), new LifterPLCConnectionEvent(this.iD, EquipmentType.ValueToString(EquipmentType.LIFTER), this.isPLCConnected));
        }
        /// <summary>
        /// CIM状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        private void _I_CIMSTATUS_ObservableValueChanged(object sender, object value)
        {
            if (Convert.ToBoolean(value) == true)
            {
                this.cimStatus = enumCimStatus.ON;
                base.PublishEvent(CimStatusEvent.FormSubject("*"), new CimStatusEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), cimStatus));
            }
            else
            {
                this.cimStatus = enumCimStatus.OFF;
                base.PublishEvent(CimStatusEvent.FormSubject("*"), new CimStatusEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), cimStatus));
            }
        }
        /// <summary>
        /// 设备报警上报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        private void _I_ALARMREPORT_ObservableValueChanged(object sender, object value)
        {
            try
            {
                if ((bool)value)
                {
                    short alarmCode = this.I_ALARMCODE;
                    this.OnFaultChange(alarmCode);
                    this.O_ALARMREPORTRPY = true;
                }
                else
                {
                    this.O_ALARMREPORTRPY = false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在[_I_ALARMREPORT_ObservableValueChanged]方法中报错", ex);
            }
        }

        /// <summary>
        /// 设备报警逻辑处理
        /// </summary>
        private void OnFaultChange(short alarmCode)
        {
            try
            {
                foreach (EcpAlarm ecpAlarm in ReportAlarms)
                {
                    if (ecpAlarm.ALID.Equals(alarmCode))
                    {
                        return;
                    }
                }
                EcpAlarm alarm = Naming.GetAlarmManager().GetAlarm((long)alarmCode);
                if (alarm == null)
                {
                    //弹窗提醒，或记录Log日志（报警代码不存在）
                    LogHelper.loggerInfo(string.Format("报警代码[{0}]在配置表中不存在", alarmCode));
                    return;
                }
                EcpAlarm reportAlarm = Naming.GetAlarmManager().CreateAlarm(alarm);
                if (reportAlarm == null)
                {
                    LogHelper.loggerInfo(string.Format("创建报警失败,报警代码[{0}]", alarmCode));
                    return;
                }
                long aLID = alarm.ALID;
                
                this.InnerPublishEvent(LifterPortEvent.LifterPortEventType.FAULT);
                //Naming.GetAlarmManager().AlarmSetReset((long)this.alarmCode, object.Equals(this.portFault, enumFault.FAULT_SET));
                lock (alarmMonitor)
                {
                    this.ReportAlarms.Add(reportAlarm);
                }
                //上报MCS AlarmReport事件
                this.SecsDriver.SendMessage("S5F1", reportAlarm);
                Thread.Sleep(20);
                //上报MCS AlarmSet事件
                this.SecsDriver.SendMessage("S6F11", "107", reportAlarm);
                Thread.Sleep(20);
                //上报MCS UnitAlarmSet事件
                this.SecsDriver.SendMessage("S6F11", "702", reportAlarm);
                LogHelper.loggerInfo(string.Format("上报MCS报警事件，报警CODE为:[{0}],报警ID为:[{1}]", alarmCode, aLID));
                LogHelper.alarmLogger($"创建报警信息，报警ID为[{reportAlarm.ALID}]");
                //推送到前端页面显示
                base.PublishEvent(AlarmShowEvent.FormSubject("*"), new AlarmShowEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), this.ReportAlarms));
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在[OnFaultChange]方法中报错", ex);
            }
        }
        
        private void InnerPublishEvent(LifterPortEvent.LifterPortEventType type)
        {
            base.PublishEvent(LifterPortEvent.FormSubject(this.elementId), new LifterPortEvent(this.ownerId, EquipmentType.ValueToString(EquipmentType.LIFTER), iD, type));
        }
        /// <summary>
        /// 设备报警复位上报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        private void _I_ALARMRESETREPORT_ObservableValueChanged(object sender, object value)
        {
            try
            {
                if ((bool)value)
                {
                    foreach (EcpAlarm ecpAlarm in this.ReportAlarms)
                    {
                        ecpAlarm.ALCD = ecpAlarm.ALCD & 127;
                        //上报MCS AlarmClearReport 事件
                        this.SecsDriver.SendMessage("S5F1", ecpAlarm);

                        Thread.Sleep(20);
                        //上报MCS AlarmClear事件
                        this.SecsDriver.SendMessage("S6F11", "106", ecpAlarm);

                        Thread.Sleep(20);
                        //上报MCS UnitAlarmClear事件
                        this.SecsDriver.SendMessage("S6F11", "701", ecpAlarm);

                        ecpAlarm.InsertAlarmHistory();
                        LogHelper.alarmLogger($"清除报警信息，报警ID为[{ecpAlarm.ALID}]");
                    }
                    if (UserManageControl.userManageControl == null)
                    {
                        UserManageControl.userManageControl = new UserManageControl();
                    }
                    UserManageControl.userManageControl.Asynchronous();

                    this.ReportAlarms.Clear();
                    this.O_ALARMRESETREPORTRPY = true;
                }
                else
                {
                    this.O_ALARMRESETREPORTRPY = false;
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// 报警复位请求回复
        /// </summary>
        /// <param name="type"></param>
        private void _I_ALARMRESETREQRPY_ObservableValueChanged(object sender, object value)
        {
            try
            {
                if ((bool)value)
                {
                    foreach (EcpAlarm ecpAlarm in this.ReportAlarms)
                    {
                        ecpAlarm.AlarmSet = false;
                        ecpAlarm.ALCD = ecpAlarm.ALCD & 127;

                        //上报MCS AlarmClearReport 事件
                        this.SecsDriver.SendMessage("S5F1", ecpAlarm);

                        Thread.Sleep(20);
                        //上报MCS AlarmClear事件
                        this.SecsDriver.SendMessage("S6F11", "106", ecpAlarm);

                        Thread.Sleep(20);
                        //上报MCS UnitAlarmClear事件
                        this.SecsDriver.SendMessage("S6F11", "701", ecpAlarm);

                        ecpAlarm.InsertAlarmHistory();
                    }

                    if (UserManageControl.userManageControl == null)
                    {
                        UserManageControl.userManageControl = new UserManageControl();
                    }
                    UserManageControl.userManageControl.Asynchronous();

                    this.ReportAlarms.Clear();

                    this.O_ALARMRESETREQ = false;
                }
            }
            catch (Exception)
            {
            }
        }
        //复位请求回复
        private void _I_RESUMERPY_ObservableValueChanged(object shender, object value)
        {
            try
            {
                if (Convert.ToBoolean(value) == true)
                {
                    this.O_RESUMEREQ = false;
                }
                else
                {
                    sCStatemode = enumSCStateMode.SC_AUTO;
                    base.PublishEvent(SCStateModeEvent.FormSubject("*"), new SCStateModeEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), sCStatemode));
                }
            }
            catch (Exception)
            {
            }
        }
        //暂停请求回复
        private void _I_PAUSERPY_ObservableValueChanged(object sender, object value)
        {
            try
            {
                if (Convert.ToBoolean(value) == true)
                {
                    this.O_PAUSEREQ = false;
                }
                else
                {
                    sCStatemode = enumSCStateMode.SC_PAUSED;
                    base.PublishEvent(SCStateModeEvent.FormSubject("*"), new SCStateModeEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), sCStatemode));
                }
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 创建CST，并改变CST状态
        /// </summary>
        /// <param name="cstID"></param>
        /// <param name="cstID64"></param>
        /// <param name="elementID"></param>
        /// <param name="subLocationID"></param>
        /// <param name="argCarrierState"></param>
        /// <param name="carrierType"></param>
        public void InstallMaterial(string cstID, string elementID, string subLocationID, CarrierState carrierStateChange, CarrierType carrierType, string idReadState, string createType)
        {
            if (string.IsNullOrEmpty(cstID))
            {
                LogHelper.loggerInfo($"在工位[{elementID}]创建物料信息时，物料ID为空");
                return;
            }
            string nowDateTimeString = Util.GetNowDateTimeString(Util.dateTimeFormat.FULL);
            Carrier carrier = Carrier.CreateCarrier(cstID, elementID, subLocationID, nowDateTimeString, CarrierState.INSTALLED, carrierType, this.HostID, idReadState, createType);
            if (carrier != null)
            {
                MaterialInfoControl.materialInfoControl.UpdateDelegate();
            }
            else
            {
                return;
            }
            Carrier carrierUnsafe = Naming.GetCarrierManager().GetCarrierUnsafe(cstID);
            //判断物料是否为空
            if (carrierUnsafe != null && carrierStateChange != CarrierState.INSTALLED)
            {
                //改变物料初始化状态
                this.CarrierStateChange(cstID, carrierStateChange);
            }
        }
        /// <summary>
        /// CST状态改变
        /// </summary>
        /// <param name="carrierID">CSTID</param>
        /// <param name="newState">CST状态</param>
        public void CarrierStateChange(string carrierID, CarrierState newState)
        {
            //获取CST
            Carrier carrierUnsafe = Naming.GetCarrierManager().GetCarrierUnsafe(carrierID);
            this.CarrierStateChange(carrierUnsafe, newState);
        }
        /// <summary>
        /// CST状态改变主逻辑
        /// </summary>
        /// <param name="carrier">CSTID</param>
        /// <param name="newState">CST状态</param>
        public void CarrierStateChange(Carrier carrier, CarrierState newState)
        {
            try
            {
                if (carrier != null)
                {
                    //设备上报WaitIn时，将物料状态更改为WaitIn状态(NONE -> WAITIN)
                    if (newState == CarrierState.WAITIN)
                    {
                        carrier.CarrierState = newState;
                        carrier.Update();
                        //给MCS上报CarrierWaitIn事件 
                        this.SecsDriver.SendMessage("S6F11", "303", this, carrier);
                        LogHelper.loggerInfo("物料给MCS上报CarrierWaitIn(303)事件,物料ID为:" + carrier.CarrierId);
                    }
                    //当物料进轿厢时，将物料状态更改为TRANSFERRING（WAITIN -> TRANSFERRING）
                    else if (carrier.CarrierState != CarrierState.TRANSFERRING && newState == CarrierState.TRANSFERRING)
                    {
                        carrier.CarrierState = newState;
                        carrier.Update();
                    }
                    //当物料出Port口时，将物料状态更改为WAITOUT（TRANSFERRING -> WAITOUT）
                    else if (newState == CarrierState.WAITOUT)
                    {
                        carrier.CarrierState = newState;
                        carrier.Update();
                        this.secsDriver.SendMessage("S6F11", "304", this, carrier);
                        LogHelper.loggerInfo("物料给MCS上报CarrierWaitOut(304)事件,物料ID为:" + carrier.CarrierId);
                    }
                    else
                    {
                        carrier.CarrierState = newState;
                        carrier.Update();
                    }
                    string msg = string.Format("物料ID为:[{0}],状态改变为{1}",carrier.CarrierId,newState);
                    LogHelper.loggerInfo(msg);
                    MaterialInfoControl.materialInfoControl.UpdateDelegate();
                }
                else
                {
                    LogHelper.loggerInfo("改变物料状态时，物料为空");
                    Console.WriteLine("改变物料状态时，物料为空");
                }
            }
            catch(Exception ex)
            {
                LogHelper.loggerError("在[CarrierStateChange]方法中报错，物料状态改变流程异常", ex);
            }
        }
        public string ConvertHostIDtoPlcID(string p)
        {
            string result;
            foreach (string current in this.LocationUnits.Keys)
            {
                if (this.LocationUnits[current].HostID.Equals(p))
                {
                    result = this.LocationUnits[current].PlcID;
                    return result;
                }
            }
            foreach (LocationUnit current2 in this.LocationUnits.Values)
            {
                if (current2.ElementId == p || current2.HostID == p || current2.PlcID == p)
                {
                    result = current2.PlcID;
                    return result;
                }
            }
            result = "";
            return result;
        }
        public string ConvertHostIDtoElementID(string p)
        {
            string result;
            foreach (LocationUnit current in this.LocationUnits.Values)
            {
                if (current.ElementId == p || current.HostID == p || current.PlcID == p)
                {
                    result = current.ElementId;
                    return result;
                }
            }
            result = "";
            return result;
        }
        public string ConvertElementIdToHostId(string p)
        {
            string result;
            foreach (string current in this.LocationUnits.Keys)
            {
                if (this.LocationUnits[current].ElementId.Equals(p))
                {
                    result = this.LocationUnits[current].HostID;
                    return result;
                }
            }
            result = "";
            return result;
        }
        public string ConvertPlcIDtoHostID(string p)
        {
            string result;
            foreach (string current in this.LocationUnits.Keys)
            {
                if (this.LocationUnits[current].PlcID.Equals(p))
                {
                    result = this.LocationUnits[current].HostID;
                    return result;
                }
            }
            result = "";
            return result;
        }
        public string ConvertPlcIDtoElementID(string p)
        {
            string result;
            foreach (string current in this.LocationUnits.Keys)
            {
                if (this.LocationUnits[current].PlcID.Equals(p))
                {
                    result = this.LocationUnits[current].ElementId;
                    return result;
                }
            }
            result = "";
            return result;
        }
        private SubSystemType GetSubSystemTypeByHostID(string hostID)
        {
            SubSystemType result;
            foreach (string current in this.subsystems.Keys)
            {
                SubSystemType subSystemType = this.GetSubSystemType(current);
                if (subSystemType == SubSystemType.VEHICLE || subSystemType == SubSystemType.LIFTERPORT)
                {
                    if (this.subsystems[current].Equals(this.HostID))
                    {
                        result = subSystemType;
                        return result;
                    }
                }
            }
            result = null;
            return result;
        }
        public SubSystemType GetSubSystemType(string ID)
        {
            SubSystemType result;
            if (this.subsystems.ContainsKey(ID))
            {
                result = this.subsystems[ID].SubSystemType;
            }
            else
            {
                foreach (SubSystem current in this.subsystems.Values)
                {
                    LocationUnit locationUnit = (LocationUnit)current;
                    if (locationUnit.HostID == ID)
                    {
                        result = current.SubSystemType;
                        return result;
                    }
                    if (locationUnit.PlcID == ID)
                    {
                        result = current.SubSystemType;
                        return result;
                    }
                }
                result = null;
            }
            return result;
        }
        public void HostControlStateChange()
        {
            switch (this.hostControlState)
            {
                case enumHostControlState.SC_OFFLINE_HOST:
                    this.SecsDriver.SendMessage("S6F11", "1", this);
                    break;
            }
            LogHelper.loggerInfo("系统HOST通讯控制状态改变，状态改变为:" + this.HostControlState.ToString());
            base.PublishEvent(HostControlStateEvent.FormSubject("*"), new HostControlStateEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), this.hostControlState));
        }
        public void HostControlStatePublish()
        {
            LogHelper.loggerInfo("系统HOST通讯控制状态改变，状态改变为:" + this.HostControlState.ToString());
            base.PublishEvent(HostControlStateEvent.FormSubject("*"), new HostControlStateEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), this.hostControlState));
        }
        public void DoChangeSCMode()
        {
            base.PublishEvent(SCStateModeEvent.FormSubject("*"), new SCStateModeEvent(this.elementId, EquipmentType.ValueToString(EquipmentType.LIFTER), this.SCStatemode));
            if (GlobalCode.ProjectCode == enumLiftProject.BMDT)
            {
                switch (this.SCStatemode)
                {
                    case enumSCStateMode.SC_PAUSED:
                        this.secsDriver.SendMessage("S6F11", "103", this);
                        break;
                    case enumSCStateMode.SC_AUTO:
                        this.secsDriver.SendMessage("S6F11", "101", this);
                        break;
                    case enumSCStateMode.SC_PAUSING:
                        this.secsDriver.SendMessage("S6F11", "105", this);
                        break;
                }
                if (this.SCStatemode == enumSCStateMode.SC_PAUSING)
                {
                    this.OnCheckPaused();
                }
            }
        }
        private void OnCheckPaused()
        {
            foreach (string current in this.Vehicles.Keys)
            {
                if (this.Vehicles[current].VehicleR_I_D == enumRIDState.RUN)
                {
                    if (!this.Vehicles[current].IsOrderEnable)
                    {
                        return;
                    }
                }
            }
            this.SCStatemode = enumSCStateMode.SC_PAUSED;
        }
        public void DoPause()
        {
            this.SCStatemode = enumSCStateMode.SC_PAUSING;
        }
        public void DoResume()
        {
            this.SCStatemode = enumSCStateMode.SC_AUTO;
        }
        public int GetNextLocationID(string destPlcID, string nextLoc_Hostid)
        {
            int num = 0;
            if (destPlcID != "" && nextLoc_Hostid != "")
            {
                string text = this.ConvertPlcIDtoElementID(destPlcID);
                if (text != null)
                {
                    LifterPort lifterPort = this.GetLifterPort(text);
                    if (lifterPort.NextLocationInfo != null)
                    {
                        foreach (string current in lifterPort.NextLocationInfo.Keys)
                        {
                            if (lifterPort.NextLocationInfo[current].NextLoc_HostId == nextLoc_Hostid)
                            {
                                num = lifterPort.NextLocationInfo[current].NextLocationID;
                            }
                        }
                        if (num < 1)
                        {
                            foreach (string current in lifterPort.NextLocationInfo.Keys)
                            {
                                if (current == nextLoc_Hostid)
                                {
                                    num = int.Parse(current);
                                }
                            }
                        }
                    }
                }
            }
            return num;
        }
        public Carrier GetCarrierByCarrierID(string xCarrierID)
        {
            Carrier carrier = null;
            Carrier result;
            if (xCarrierID == "")
            {
                result = carrier;
            }
            else
            {
                carrier = Naming.GetCarrierManager().GetCarrier(xCarrierID);
                if (xCarrierID != null)
                {
                    result = carrier;
                }
                else
                {
                    carrier = Naming.GetCarrierManager().GetCarrier64(xCarrierID);
                    result = carrier;
                }
            }
            return result;
        }

        public LifterPort GetLifterPortByPLCID(string plcId)
        {
            LifterPort result;
            if (string.IsNullOrEmpty(plcId))
            {
                result = null;
            }
            else
            {
                foreach (LifterPort current in this.LifterPorts.Values)
                {
                    if (current.PlcID == plcId)
                    {
                        result = current;
                        return result;
                    }
                }
                result = null;
            }
            return result;
        }
        /// <summary>
        /// 改变aim状态，并上报Host
        /// </summary>
        private void OnDeviceStateChange()
        {
            enumAIMDeviceState newEnumAIMDeviceState = enumAIMDeviceState.OutofService;
            if (this.deviceState == enumRIDState.DOWN)
            {
                newEnumAIMDeviceState = enumAIMDeviceState.OutofService;
                //this.DoPause();
                this.systemNoAlarmEndTime = DateTime.Now;
                this.AddDataStatisticByDay(statisticTimeType.SYSTEMNOALARMTIME);
                if (this.shuttleMaster.TransferStatus == ShuttleMaster.ShuttleTransferStatus.Move)
                {
                    //记录搬送结束时间
                    this.transferEndTime = DateTime.Now;
                    this.AddDataStatisticByDay(LifterSEM.statisticTimeType.TRANSFERTIME);
                }
            }
            else
            {
                newEnumAIMDeviceState = enumAIMDeviceState.InService;
                this.systemNoAlarmStartTime = DateTime.Now;
            }
            if (this.deviceStateForAim != newEnumAIMDeviceState)
            {
                this.deviceStateForAim = newEnumAIMDeviceState;
                if (newEnumAIMDeviceState == enumAIMDeviceState.InService)
                {
                    this.SecsDriver.SendMessage("S6F11", "501", this);
                    //执行初始化动作
                    this.ShuttleMaster.MachineAlarmResumeAction();
                }
                else
                {
                    this.SecsDriver.SendMessage("S6F11", "502", this);
                    //设备重报警动作执行
                    this.ShuttleMaster.MachineAlarmPauseAction();
                }
            }
        }
        private void OnCheckPLCConnect(bool value)
        {
            if (!value)
            {
                LogHelper.loggerInfo("PLC通讯连接已终止");
            }
        }
        /// <summary>
        /// check系统是否在设置的时间内。如果超过设置的时间，则自动登出
        /// </summary>
        internal void CheckLogInTime()
        {
            if (this.LoginTimeCount > 0 && this.userPrivilige)
            {
                if (this.LoginTimeCount > 1800)
                {
                    this.UserPrivilige = false;
                    this.UserPower = enumUserManage.Operation.ToString();
                    LifterMainForm lifterMainForm = (LifterMainForm)SimpleCache.GetObject("FormMain", "LifterMainForm");
                    lifterMainForm.InitPowerControl();

                    //初始化
                    AllConfigControl allConfigControl = (AllConfigControl)SimpleCache.GetObject("FormMain", "AllConfigControl");
                    allConfigControl.InitPowerMenu();
                    AllHistoryControl allHistoryControl = (AllHistoryControl)SimpleCache.GetObject("FormMain", "AllHistoryControl");
                    allHistoryControl.InitPowerMenu();
                    SystemsDisplay systemsDisplay = (SystemsDisplay)SimpleCache.GetObject("FormMain", "SystemsDisplay");
                    systemsDisplay.InitPowerMenu();
                    InformPanel informPanel = (InformPanel)SimpleCache.GetObject("FormMain", "InformPanel");
                    informPanel.InitPowerMenu();
                }
                else
                {
                    this.LoginTimeCount++;
                }
            }
        }
        internal void OnTimeSync()
        {
            this.secsDriver.SendMessage("S2F17", this);
        }
        private void SyncPCLTimeSet(Util.SYSTEMTIME setTime)
        {
            this.O_YEARDATASET = (short)setTime.wYear;
            this.O_MONTHDATASET = (short)setTime.wMonth;
            this.O_DAYDATASET = (short)setTime.wDay;
            this.O_TIMESETDATAHH = (short)setTime.wHour;
            this.O_TIMESETDATAMM = (short)setTime.wMinute;
            this.O_TIMESETDATASS = (short)setTime.wSecond;
            this.O_TIMESETREQ = true;
            string str = string.Concat(new string[]
            {
                "时间同步, ",
                setTime.wYear.ToString(),
                "年",
                setTime.wMonth.ToString(),
                "月",
                setTime.wDay.ToString(),
                "日",
                setTime.wHour.ToString(),
                "时",
                setTime.wMinute.ToString(),
                "分",
                setTime.wSecond.ToString(),
                " 秒"
            });
        }
        public string GetDeviceID(string elementId)
        {
            string result;
            foreach (LocationUnit current in this.LocationUnits.Values)
            {
                if (current.ElementId == elementId || current.HostID == elementId || current.PlcID == elementId)
                {
                    result = current.HostID;
                    return result;
                }
            }
            result = "";
            return result;
        }

        public string GetDispName(string strID, string subLocationID)
        {
            LocationUnit locationUnit = this.GetLocationUnit(strID);
            string result;
            if (locationUnit == null)
            {
                result = "";
            }
            else
            {
                if (locationUnit is Vehicle)
                {
                    result = locationUnit.HostID;
                }
                else
                {
                    if (locationUnit is LifterPort)
                    {
                        if (string.IsNullOrEmpty(subLocationID))
                        {
                            result = locationUnit.HostID;
                        }
                        else
                        {
                            LifterPort lifterPort = locationUnit as LifterPort;
                            result = locationUnit.HostID;
                        }
                    }
                    else
                    {
                        result = "";
                    }
                }
            }
            return result;
        }
        public string GetDispName(string strID)
        {
            return this.GetDispName(strID, "1");
        }
        public LocationUnit GetLocationUnit(string strID)
        {
            LocationUnit result;
            if (this.LocationUnits.ContainsKey(strID))
            {
                result = this.LocationUnits[strID];
            }
            else
            {
                foreach (LocationUnit current in this.LocationUnits.Values)
                {
                    if (current.HostID == strID || current.PlcID == strID)
                    {
                        result = current;
                        return result;
                    }
                }
                result = null;
            }
            return result;
        }
        public string GetUnitHostID(string strID)
        {
            string result;
            if (this.LocationUnits.ContainsKey(strID))
            {
                result = this.LocationUnits[strID].HostID;
            }
            else
            {
                foreach (LocationUnit current in this.LocationUnits.Values)
                {
                    if (current.HostID.Trim() == strID || current.PlcID == strID)
                    {
                        result = current.HostID;
                        return result;
                    }
                }
                result = "";
            }
            return result;
        }
        public string GetUnitElementID(string strID)
        {
            string result;
            if (this.LocationUnits.ContainsKey(strID))
            {
                result = this.LocationUnits[strID].HostID;
            }
            else
            {
                foreach (LocationUnit current in this.LocationUnits.Values)
                {
                    if (current.HostID == strID || current.PlcID == strID)
                    {
                        result = current.ElementId;
                        return result;
                    }
                }
                result = "";
            }
            return result;
        }
        public enumAimTransferState ConvertMCSTrasferState(enumTransferState tState)
        {
            enumAimTransferState result;
            if (tState == enumTransferState.NONE || tState == enumTransferState.CREATE)
            {
                result = enumAimTransferState.QUEUED;
            }
            else if (tState == enumTransferState.TRANSFERRING)
            {
                result = enumAimTransferState.TRANSFERRING;
            }
            else if (tState == enumTransferState.PAUSED)
            {
                result = enumAimTransferState.PAUSED;
            }
            else if (tState == enumTransferState.CANCELING)
            {
                result = enumAimTransferState.CANCELING;
            }
            else if (tState == enumTransferState.ABORTING)
            {
                result = enumAimTransferState.ABORTING;
            }
            else
            {
                result = enumAimTransferState.NONE;
            }
            return result;
        }
        /// <summary>
        /// 获取当前楼层unloadCV
        /// </summary>
        /// <returns></returns>
        public List<ConveyorBuffer> GetUnLoadCV()
        {
            //获取当前楼层的出料CV
            List<ConveyorBuffer> unloadCVs = new List<ConveyorBuffer>();
            foreach (ConveyorBuffer conveyorBuffer in this.ConveyorBuffers.Values)
            {
                if (ConveyorBuffer.Constants.CVUNLOAD.Equals(conveyorBuffer.Cvtype))
                {
                    unloadCVs.Add(conveyorBuffer);
                }
            }
            return unloadCVs;
        }
        /// <summary>
        /// WaitIn上报后，MCS下指令超时逻辑，超时则PC自动创建指令，并上报MCS
        /// </summary>
        public void CreateCarrierCommandByTimeOut()
        {
            try
            {
                //判断系统运行模式是否为AUTO模式
                if (this.SCStatemode == enumSCStateMode.SC_AUTO)
                {
                    //循环每个Port口
                    foreach (LifterPort current in this.LifterPorts.Values)
                    {
                        this.PCAutoCreateCommandOnPort(current);
                    }
                    List<ConveyorBuffer> UnLoadCVs = this.GetUnLoadCV();
                    //循环判断每个CV
                    foreach (ConveyorBuffer unloadCV in UnLoadCVs)
                    {
                        this.PCAutoCreateCommandOnCV(unloadCV);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在[CreateCarrierCommandByTimeOut]方法中报错", ex);
            }
        }
        /// <summary>
        /// PC在CV超时自动创建指令
        /// </summary>
        /// <param name="lifterPort"></param>
        private void PCAutoCreateCommandOnCV(ConveyorBuffer UnLoaderCV)
        {
            LifterPort lifterPortbyCV = this.GetLifterPort(UnLoaderCV.LifterPortID);
            //判断每个port状态是否为WAIT_IN状态
            if (UnLoaderCV.WaitIn == PortWIWO.WAIT_IN)
            {
                //WaitInTime表示waitin/waitout发生时的当前时间
                if (UnLoaderCV.WaitInTime.Equals(DateTime.MinValue))
                {
                    UnLoaderCV.WaitInTime = DateTime.Now;
                }
                if (!UnLoaderCV.InService)
                {
                    UnLoaderCV.WaitInTime = DateTime.MinValue;
                }
                else
                {
                    if (lifterPortbyCV.PortHandoffType != HandOffType.MGV || this.hostControlState == enumHostControlState.SC_ONLINE_HOST)
                    {
                        //在Online模式下，等待MCS指令超时，PC自动创建指令
                        if (this.hostControlState == enumHostControlState.SC_ONLINE_HOST && lifterPortbyCV.IsUSECVWaitTimeOut)
                        {
                            string WaitInTimeOut_ExitMaterialFlag_PropVal = this.GetUserDefinedPropertyValue("WaitInTimeOut_ExitMaterialFlag", "F", true);
                            //MCS指令超时，设备是否需要退料流程
                            if ("T".Equals(WaitInTimeOut_ExitMaterialFlag_PropVal.Trim()))
                            {
                                //设备退料流程
                                //弹窗提醒，或记录Log日志
                                LogHelper.loggerInfo("在PCAutoCreateCommandOnCV方法中，MCS指令超时，设备退料流程");

                            }
                            else
                            {
                                //判断MCS指令超时时间是否为0
                                if (this.CvWaitInCountLimit != 0)
                                {
                                    int WaitInTimeOut = Util.GetGapTime1toNow(Util.DateFormat.SECOND, UnLoaderCV.WaitInTime);
                                    if (WaitInTimeOut >= this.CvWaitInCountLimit && !UnLoaderCV.IsHostCommandTimeOut)
                                    {
                                        UnLoaderCV.PCAutoCreateCommand(lifterPortbyCV);
                                        UnLoaderCV.IsHostCommandTimeOut = true;
                                    }
                                }
                            }
                        }
                        //在Offline模式下，PC自动创建指令
                        else if (this.hostControlState != enumHostControlState.SC_ONLINE_HOST)
                        {
                            if (lifterPortbyCV.IsUSEOfflineAutoCMD)
                            {
                                UnLoaderCV.PCAutoCreateCommand(lifterPortbyCV);
                            }
                        }
                        else
                        {
                            //弹窗显示，当前模式无法创建指令
                            LogHelper.loggerInfo($"当前controlState[{this.hostControlState}]模式，无法自动创建指令");
                        }
                    }
                    else
                    {
                        if (lifterPortbyCV.IsUSEOfflineAutoCMD)
                        {
                            UnLoaderCV.PCAutoCreateCommand(lifterPortbyCV);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// PC在Port口超时自动创建指令
        /// </summary>
        /// <param name="lifterPort"></param>
        private void PCAutoCreateCommandOnPort(LifterPort lifterPort)
        {
            //判断每个port状态是否为WAIT_IN状态,并且 Port模式不是MGV模式
            if (lifterPort.WaintIn == PortWIWO.WAIT_IN && !lifterPort.IsCombine)
            {
                //WaitInTime表示waitin/waitout发生时的当前时间
                if (lifterPort.WaitInTime.Equals(DateTime.MinValue))
                {
                    lifterPort.WaitInTime = DateTime.Now;
                }
                if (lifterPort.LifterPortState == enumRIDState.DOWN)
                {
                    lifterPort.WaitInTime = DateTime.MinValue;
                }
                else
                {
                    if (lifterPort.PortHandoffType != HandOffType.MGV || this.HostControlState == enumHostControlState.SC_ONLINE_HOST)
                    {
                        //在Online模式下，等待MCS指令超时，PC自动创建指令
                        if (this.hostControlState == enumHostControlState.SC_ONLINE_HOST && lifterPort.IsUSECVWaitTimeOut)
                        {
                            string WaitInTimeOut_ExitMaterialFlag_PropVal = this.GetUserDefinedPropertyValue("WaitInTimeOut_ExitMaterialFlag", "F", true);
                            //MCS指令超时，设备是否需要退料流程
                            if ("T".Equals(WaitInTimeOut_ExitMaterialFlag_PropVal.Trim()))
                            {
                                //设备退料流程
                                //弹窗提醒，或记录Log日志
                                LogHelper.loggerInfo("在PCAutoCreateCommandOnCV方法中，MCS指令超时，设备退料流程");
                            }
                            else
                            {
                                //判断MCS指令超时时间是否为0
                                if (this.CvWaitInCountLimit != 0)
                                {
                                    int WaitInTimeOut = Util.GetGapTime1toNow(Util.DateFormat.SECOND, lifterPort.WaitInTime);
                                    if (WaitInTimeOut >= this.CvWaitInCountLimit && !lifterPort.IsHostCommandTimeOut)
                                    {
                                        lifterPort.PCAutoCreateCommand();
                                        lifterPort.IsHostCommandTimeOut = true;
                                    }
                                }
                            }
                        }
                        //在Offline模式下，PC自动创建指令
                        else if (this.hostControlState != enumHostControlState.SC_ONLINE_HOST)
                        {
                            if (lifterPort.IsUSEOfflineAutoCMD)
                            {
                                lifterPort.PCAutoCreateCommand();
                            }
                        }
                        else
                        {
                            //弹窗显示，当前模式无法创建指令
                            //
                            //
                        }
                    }
                    else
                    {
                        if (this.hostControlState != enumHostControlState.SC_ONLINE_HOST)
                        {
                            if (lifterPort.IsUSEOfflineAutoCMD)
                            {
                                lifterPort.PCAutoCreateCommand();
                            }
                        }
                        else
                        {
                            //弹窗显示，当前模式无法创建指令
                            //
                            //
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Check上层系统（MCS/MES）下发的指令是否正确：
        /// --1.check指令的物料ID是否为空,起始地/目的地是否为空；
        /// --2.判断起始地Port的物料是否为空
        /// --3.若起始地/目的地都不为空，则判断起始地的物料ID与指令的物料ID是否一致
        /// --4.判断此物料ID的物料对象是否存在
        /// --5.判断此物料的当前位置是否是当前的Port口（存在残留的物料）
        /// </summary>
        /// <param name="carrierId"></param>
        /// <param name="strSource"></param>
        /// <param name="strDest"></param>
        /// <param name="Description"></param>
        /// <returns></returns>
        public enumNewTrasferCmdAvailable CheckNewTrasferCmdAvailable(string carrierId, string strSource, string strDest, out string Description)
        {
            enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NONE;
            Description = "";
            bool flag = false;
            bool flag2 = false;
            bool flag3 = false;
            enumNewTrasferCmdAvailable result;
            //指令的物料ID为空
            if (string.IsNullOrEmpty(carrierId))
            {
                enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_ID_WRONG;
                Description = "CarrierID is Wrong";
                result = enumNewTrasferCmdAvailable;
            }
            else
            {
                //根据指令的起始地判断是否存在Port对象
                LifterPort lifterPort = this.GetLifterPort(strSource);
                if (lifterPort == null)
                {
                    enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                    Description = "Source is Wrong";
                    flag = true;
                }
                //如果起始地是轿厢，则判断是否为空
                Vehicle vehicle = this.GetVehicle(strSource);
                if (vehicle == null)
                {
                    enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                    Description = "Source is Wrong";
                    flag2 = true;
                }
                //如果起始地是CV，则判断是否为空
                ConveyorBuffer conveyorBuffer = this.GetConveyorBuffer(strSource);
                if (conveyorBuffer == null)
                {
                    enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                    Description = "Source is Wrong";
                    flag3 = true;
                }
                if (flag && flag2 && flag3)
                {
                    result = enumNewTrasferCmdAvailable;
                }
                else
                {
                    //根据指令的目的地判断是否存在Port对象
                    LifterPort lifterPort2 = this.GetLifterPort(strDest);
                    if (lifterPort2 == null)
                    {
                        enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_WRONG;
                        Description = "Dest is wrong";
                        result = enumNewTrasferCmdAvailable;
                    }
                    else
                    {
                        //起始地、目的地都存在的情况
                        if (lifterPort != null)
                        {
                            enumNewTrasferCmdAvailable = this.CheckNewTrasferCmdAvailable(carrierId, lifterPort, lifterPort2, out Description);
                        }
                        else if (vehicle != null)
                        {
                            //起始地为轿厢，且不为空
                            enumNewTrasferCmdAvailable = this.CheckNewTrasferCmdAvailable(carrierId, vehicle, lifterPort2, out Description);
                        }
                        else
                        {
                            //起始地为轿厢，且不为空
                            enumNewTrasferCmdAvailable = this.CheckNewTrasferCmdAvailable(carrierId, conveyorBuffer, lifterPort2, out Description);
                        }
                        result = enumNewTrasferCmdAvailable;
                    }
                }
            }
            return result;
        }
        public enumNewTrasferCmdAvailable CheckNewTrasferCmdAvailable(string CommandCarrierId, LifterPort srcPort, LifterPort destPort, out string Description)
        {
            Description = "";
            enumNewTrasferCmdAvailable result;
            //获取物料对象
            Carrier carrier = Naming.GetCarrierManager().GetCarrier(CommandCarrierId);
            if (srcPort == null)
            {
                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                Description = "Carrier location is Wrong";
                result = enumNewTrasferCmdAvailable;
            }
            else
            {
                //判断传输物料是否为空
                string transferCstID = srcPort.CarrierId;
                if (string.IsNullOrEmpty(transferCstID))
                {
                    //从PLC获取实时的物料ID
                    transferCstID = srcPort.GetCarrierIDFromPLC();
                    if (string.IsNullOrEmpty(transferCstID.Trim()))
                    {
                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_SRC_PORT_IS_NOT_WAIT_IN;
                        Description = "Source port is Not WAIT IN(No CST ID)";
                        result = enumNewTrasferCmdAvailable;
                        return result;
                    }
                    srcPort.CarrierId = transferCstID;
                }
                else
                {
                    transferCstID = srcPort.CarrierId;
                }
                //判断指令的物料ID跟传输的物料ID是否一致
                if (CommandCarrierId != transferCstID)
                {
                    enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_SRC_PORT_IS_NOT_WAIT_IN;
                    Description = "Wrong CarrierID. WAIT IN ERROR";
                    result = enumNewTrasferCmdAvailable;
                }
                else
                {
                    if (carrier.CarrierState != CarrierState.WAITIN)
                    {
                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_NOT_WAIT_IN;
                        Description = "Carrier[" + CommandCarrierId + "] IS NOT W.I";
                        result = enumNewTrasferCmdAvailable;
                    }
                    //判断起始地是否是WaitIn状态
                    if (srcPort.WaintIn != PortWIWO.WAIT_IN)
                    {
                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_SRC_PORT_IS_NOT_WAIT_IN;
                        Description = "Source Port[" + srcPort.HostID + "] IS NOT W.I";
                        result = enumNewTrasferCmdAvailable;
                    }
                    else
                    {
                        //判断目的地Port口的方向是否为Out模式
                        if (destPort.PortInOutMode != enumLifterPortDirection.OUT)
                        {
                            enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_DIRECTION_WRONG;
                            Description = "Dest port is not Out-Direction";
                            result = enumNewTrasferCmdAvailable;
                        }
                        else
                        {
                            //判断目的地的状态是否为down
                            if (destPort.LifterPortState == enumRIDState.DOWN)
                            {
                                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_DOWN;
                                Description = "Dest is Down";
                                result = enumNewTrasferCmdAvailable;
                            }
                            else
                            {
                                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.AVAIL;
                                result = enumNewTrasferCmdAvailable;
                            }
                        }
                    }
                }
            }
            return result; 
        }
        public enumNewTrasferCmdAvailable CheckNewTrasferCmdAvailable(string carrierId, Vehicle vehicle, LifterPort destPort, out string Description)
        {
            Description = "";
            Carrier carrier = Naming.GetCarrierManager().GetCarrier(carrierId);
            enumNewTrasferCmdAvailable result;
            if (carrier == null)
            {
                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_NO_CARRIER;
                Description = "Carrier is invalid";
                result = enumNewTrasferCmdAvailable;
            }
            else
            {
                if (vehicle == null)
                {
                    enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                    Description = "Carrier location is Wrong";
                    result = enumNewTrasferCmdAvailable;
                }
                else
                {
                    if (vehicle.HostID != carrier.CarrierLoc)
                    {
                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_MISMATCH_SRC;
                        Description = "Carrier location is differnt src";
                        result = enumNewTrasferCmdAvailable;
                    }
                    else
                    {
                        TransferWorkItem workItemByCarrierID = this.LDispatcher.GetWorkItemByCarrierID(carrier.CarrierId);
                        if (workItemByCarrierID != null)
                        {
                            enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_HAVE_COMMAND;
                            Description = "Carrier has already Command.";
                            result = enumNewTrasferCmdAvailable;
                        }
                        else
                        {
                            if (destPort == null)
                            {
                                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_WRONG;
                                Description = "Dest is wrong";
                                result = enumNewTrasferCmdAvailable;
                            }
                            else
                            {
                                if (destPort.PortInOutMode != enumLifterPortDirection.OUT)
                                {
                                    enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_DIRECTION_WRONG;
                                    Description = "Dest port is not Out-Direction";
                                    result = enumNewTrasferCmdAvailable;
                                }
                                else
                                {
                                    if (destPort.LifterPortState == enumRIDState.DOWN)
                                    {
                                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_DOWN;
                                        Description = "Dest is Down";
                                        result = enumNewTrasferCmdAvailable;
                                    }
                                    else
                                    {
                                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.AVAIL;
                                        result = enumNewTrasferCmdAvailable;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
        public enumNewTrasferCmdAvailable CheckNewTrasferCmdAvailable(string carrierId, ConveyorBuffer conveyorBuffer, LifterPort destPort, out string Description)
        {
            Description = "";
            Carrier carrier = Naming.GetCarrierManager().GetCarrier(carrierId);
            enumNewTrasferCmdAvailable result;
            if (carrier == null)
            {
                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_NO_CARRIER;
                Description = "Carrier is invalid";
                result = enumNewTrasferCmdAvailable;
            }
            else
            {
                if (conveyorBuffer == null)
                {
                    enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                    Description = "Carrier location is Wrong";
                    result = enumNewTrasferCmdAvailable;
                }
                else
                {
                    if (conveyorBuffer.HostID != carrier.CarrierLoc)
                    {
                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_MISMATCH_SRC;
                        Description = "Carrier location is differnt src";
                        result = enumNewTrasferCmdAvailable;
                    }
                    else
                    {
                        TransferWorkItem workItemByCarrierID = this.LDispatcher.GetWorkItemByCarrierID(carrier.CarrierId);
                        if (workItemByCarrierID != null)
                        {
                            enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_HAVE_COMMAND;
                            Description = "Carrier has already Command.";
                            result = enumNewTrasferCmdAvailable;
                        }
                        else
                        {
                            if (destPort == null)
                            {
                                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_WRONG;
                                Description = "Dest is wrong";
                                result = enumNewTrasferCmdAvailable;
                            }
                            else
                            {
                                if (destPort.PortInOutMode != enumLifterPortDirection.OUT)
                                {
                                    enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_DIRECTION_WRONG;
                                    Description = "Dest port is not Out-Direction";
                                    result = enumNewTrasferCmdAvailable;
                                }
                                else
                                {
                                    if (destPort.LifterPortState == enumRIDState.DOWN)
                                    {
                                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_DOWN;
                                        Description = "Dest is Down";
                                        result = enumNewTrasferCmdAvailable;
                                    }
                                    else
                                    {
                                        enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.AVAIL;
                                        result = enumNewTrasferCmdAvailable;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
        public enumNewTrasferCmdAvailable CheckNewTrasferCmdManual(string carrierId, string strSource, string strDest, out string Description)
        {
            enumNewTrasferCmdAvailable result;
            Description = "";
            result = enumNewTrasferCmdAvailable.AVAIL;
            //指令的物料ID为空
            if (string.IsNullOrEmpty(carrierId))
            {
                result = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_ID_WRONG;
                Description = "CarrierID is Wrong";
                return result;
            }
            else
            {
                //判断物料是否已经存在指令
                TransferWorkItem transferWorkItemByCarrierID = this.LDispatcher.GetJobByCarrierID(carrierId);
                if (transferWorkItemByCarrierID != null)
                {
                    result = enumNewTrasferCmdAvailable.NOT_AVAIL_COMMANDISEXIST;
                    Description = "指令已存在，请重新添加";
                    return result;
                }
                //shuttleMaster的状态
                if (shuttleMaster.ShuttleMasterStatus == enumRIDState.DOWN)
                {
                    result = enumNewTrasferCmdAvailable.NOT_AVAIL_SHUTTLESTATUS_ISDOWN;
                    Description = "轿厢状态为Down";
                    return result;
                }
                //根据指令的起始地判断是否存在对象
                LifterPort lifterPort = this.GetLifterPort(strSource);
                ConveyorBuffer conveyorBuffer = this.GetConveyorBuffer(strSource);
                if (lifterPort != null  || conveyorBuffer != null)
                {
                    //判断起始地状态
                    if (lifterPort != null)
                    {
                        if (lifterPort.LifterPortState == enumRIDState.DOWN)
                        {
                            result = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                            Description = "起始地["+ lifterPort.HostID +"]状态为Down";
                            return result;
                        }
                    }
                    if (conveyorBuffer != null)
                    {
                        LifterPort CVlifterPort = this.GetLifterPort(conveyorBuffer.LifterPortID);
                        if (CVlifterPort.LifterPortState == enumRIDState.DOWN)
                        {
                            result = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                            Description = "起始地[" + conveyorBuffer.HostID + "]状态为Down";
                            return result;
                        }
                    }
                }
                else
                {
                    result = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                    Description = "起始地为空";
                    return result;
                }
                //判断目的地是否合法
                LifterPort lifterPort1 = this.GetLifterPort(strDest);
                if (lifterPort1 != null)
                {
                    if (lifterPort1.LifterPortState == enumRIDState.DOWN)
                    {
                        result = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_WRONG;
                        Description = "目的地[" + lifterPort1.HostID + "]状态为Down";
                        return result;
                    }
                }
                else
                {
                    result = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_WRONG;
                    Description = "目的地为空";
                    return result;
                }
            }
            return result;
        }
        private enumNewTrasferCmdAvailable DestTransferAvailable(string strDest, out string Description)
        {
            enumNewTrasferCmdAvailable result;
            //根据指令的目的地判断是否存在Port对象
            LifterPort lifterPort2 = this.GetLifterPort(strDest);
            if (lifterPort2 == null)
            {
                enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_WRONG;
                Description = "Dest is wrong";
                result = enumNewTrasferCmdAvailable;
            }
            else
            {
                //判断指令的目的地的状态
                if (lifterPort2.LifterPortState == enumRIDState.DOWN)
                {
                    enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.NOT_AVAIL_CARRIER_LOCATION_WRONG;
                    Description = "Dest Status is Wrong";
                    result = enumNewTrasferCmdAvailable;
                }
                else
                {
                    enumNewTrasferCmdAvailable enumNewTrasferCmdAvailable = enumNewTrasferCmdAvailable.AVAIL;
                    Description = "Transfer Create is Success";
                    result = enumNewTrasferCmdAvailable;
                }
            }
            return result;
        }
        public void CarriedToPlc(string carrierId, string strSource)
        {
            //根据指令的起始地判断是否存在对象
            LifterPort lifterPort = this.GetLifterPort(strSource);
            Vehicle vehicle = this.GetVehicle(strSource);
            ConveyorBuffer conveyorBuffer = this.GetConveyorBuffer(strSource);
            if (lifterPort != null || vehicle != null || conveyorBuffer != null)
            {
                //判断起始地状态
                if (lifterPort != null)
                {
                    lifterPort.SetCSTIDtoPLCBuffer(1, carrierId);
                }
                if (conveyorBuffer != null)
                {
                    conveyorBuffer.SetCSTIDtoPLC(carrierId);
                }
                if (vehicle != null)
                {
                    vehicle.SetCSTIDtoPLC(carrierId);
                }
            }
        }
        public void StartTimer()
        {
            this.mainTimer.Change(0, 1000);
        }
        public void StopTimer()
        {
            this.mainTimer.Change(-1, 1000);
        }
        public void SubProcessTimerCall()
        {
            this.mainTimer.Change(-1, 1000);
            //LogFormat.AddLog(MessageType.TDPS, this.hostID, "/1/2/3/4/5/6/7/8/9");
            this.mainTimer.Change(1000, 1000);
        }
        private void SecsDriverEventDelegate()
        {
            this.secsDriver.OnAbortMessage += new AbortMessage(this.secsDriver_OnAbortMessage);
            this.secsDriver.OnConnected += new Connected(this.secsDriver_OnConnected);
            this.secsDriver.OnDisconnected += new Disconnected(this.secsDriver_OnDisconnected);
            this.secsDriver.OnInvalidMessage += new ReceivedInvalidMessage(this.secsDriver_OnInvalidMessage);
            this.secsDriver.OnReceiveMessage += new ReceivedMessage(this.secsDriver_OnReceiveMessage);
            this.secsDriver.OnUnknownMessage += new UnknownMessage(this.secsDriver_OnUnknownMessage);
        }
        private void secsDriver_OnUnknownMessage(object sender, SecsEventArgs e)
        {
            LogHelper.loggerInfo("/HOST/UNKNOWN_MSG/" + e.MessageBody);
        }
        private void secsDriver_OnInvalidMessage(object sender, SecsEventArgs e)
        {
            LogHelper.loggerInfo("/HOST/INVALID_MSG/" + e.MessageBody);
        }
        private void secsDriver_OnDisconnected(object sender, SecsEventArgs e)
        {
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetLifter();
            this.hostControlState = enumHostControlState.SC_OFFLINE_HOST;
            this.DoPause();
            LogHelper.loggerInfo("/SECS/DRIVER/DISCONNECTED.");
        }
        private void secsDriver_OnConnected(object sender, SecsEventArgs e)
        {
            this.hostControlState = enumHostControlState.SC_OFFLINE_HOST;
            LogHelper.loggerInfo("/SECS/DRIVER/CONNECTED.");
        }
        private void secsDriver_OnAbortMessage(object sender, SecsEventArgs e)
        {
            LogHelper.loggerInfo("/HOST/ABORT_MSG/" + e.MessageBody);
        }
        /// <summary>
        /// 接收消息，返回对应的消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void secsDriver_OnReceiveMessage(object sender, SecsEventArgs e)
        {
            string strSxFx = "S" + e.Stream + "F" + e.Function;
            switch (strSxFx)
            {
                case "S1F1":
                    this.ReplyS1F1(strSxFx, e);
                    break;
                case "S1F3":
                    this.ReplyS1F3(strSxFx, e);
                    break;
                case "S1F13":
                    this.ReplyS1F13(strSxFx, e);
                    break;
                case "S1F15":
                    this.ReplyS1F15(strSxFx, e);
                    break;
                case "S1F17":
                    this.ReplyS1F17(strSxFx, e);
                    break;
                case "S2F13":
                    this.ReplyS2F13(strSxFx, e);
                    break;
                case "S2F15":
                    this.ReplyS2F15(strSxFx, e);
                    break;
                case "S2F17":
                    this.ReceiveS2F17(strSxFx, e);
                    break;
                case "S2F18":
                    this.ReceiveS2F18(strSxFx, e);
                    break;
                case "S2F31":
                    this.ReplyS2F31(strSxFx, e);
                    break;
                case "S2F33":
                    this.ReplyS2F33(strSxFx, e);
                    break;
                case "S2F41":
                    this.ReplyS2F41(strSxFx, e);
                    break;
                case "S2F49":
                    this.ReplyS2F49(strSxFx, e);
                    break;
                case "S5F3":
                    this.ReplyS5F3(strSxFx, e);
                    break;
                case "S10F3":
                    this.ReplyS10F3(strSxFx, e);
                    break;
            }
        }
        private void ReceiveS2F17(string sxfx, SecsEventArgs e)
        {
        }
        private void ReplyS2F15(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            SXTransaction sXTransaction = (SXTransaction)e.SecsTransaction;
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            int nECIDCount = int.Parse(secsValue.GetValue("ECIDCOUNT"));
            for (int i = 0; i < nECIDCount; i++)
            {
                string value = secsValue.GetValue(i.ToString());
                string[] array = value.Split(new char[]
                {
                    ','
                });
                string text = array[0];
                string text2 = array[1];
                secsValue.SetRequestValue(i.ToString(), "1");
            }
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
        }
        private void ReplyS2F13(string sxfx, SecsEventArgs e)
        {
        }
        private void ReplyS1F1(string sxfx, SecsEventArgs e)
        {
            e.SecsTransaction = S1F1.MakeTransactionACK();
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
        }
        private void ReplyS1F13(string sxfx, SecsEventArgs e)
        {
            //获取S1F13 reply事件
            e.SecsTransaction = S1F13.makeTransaction();
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
        }
        private void ReplyS1F15(string sxfx, SecsEventArgs e)
        {
            e.SecsTransaction = S1F16.MakeTransactionSend();
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
            this.HostControlState = enumHostControlState.SC_OFFLINE_HOST;
        }
        private void ReplyS1F17(string sxfx, SecsEventArgs e)
        {
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetLifter();
            string msgAck = "";
            bool flag = true;
            if (this.HostControlState == enumHostControlState.SC_ONLINE_HOST)
            {
                msgAck = ((int)MsgACK.ONLACK.EquipmentAlreadyOnLineRemote).ToString();
                LogHelper.loggerInfo(sxfx + "Online Request [Result: Equipment Already OnLine Remote]");
                flag = false;
            }
            else
            {
                msgAck = ((int)MsgACK.ONLACK.OnLineRemoteConfirmed).ToString();
                LogHelper.loggerInfo(sxfx + "Online Request [Result: Equipment OnLine Remote Not Allowew]");
                flag = true;
            }
            e.SecsTransaction = S1F18.makeTransaction(msgAck);
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
            if (flag)
            {
                lifterSEM.HostControlState = enumHostControlState.SC_ONLINE_HOST;
            }
        }
        private void ReplyS1F3(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            e.SecsTransaction = S1F4.MakeTransactionSend(this,e);
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
            LogHelper.loggerInfo("Reply S1F3 Report Send Complete(S1F3 VID ALL 已发送消息).");
        }
        public void makeListS1F3EnhancedCarrier(ref SXTransaction transaction)
        {
            this.ClearInvalidMaterial();
            Carrier[] carrierCopyAll = Naming.GetCarrierManager().GetCarrierCopyAll();
            if (carrierCopyAll == null || carrierCopyAll.Length == 0)
            {
                transaction.WriteNode(SX.SECSFormat.L, 0, "", "EnhancedCarrier", new int[0]);
            }
            else
            {
                transaction.WriteNode(SX.SECSFormat.L, carrierCopyAll.Length, "", "EnhancedCarriers[11]", new int[0]);
                Carrier[] array = carrierCopyAll;
                for (int i = 0; i < array.Length; i++)
                {
                    Carrier carrier = array[i];
                    transaction.WriteNode(SX.SECSFormat.L, 3, "", "EnhancedCarrierInfo[12]", new int[0]);
                    transaction.WriteNode(SX.SECSFormat.A, 0, this.hostID, "LifetrName[15]", new int[0]);
                    transaction.WriteNode(SX.SECSFormat.A, 0, carrier.CarrierId, "Carrier ID[3]", new int[0]);
                    //transaction.WriteNode(SX.SECSFormat.A, 0, this.GetDispName(carrier.CarrierLoc, carrier.CarrierSubLoc), "Carrier Location[4]", new int[0]);
                    transaction.WriteNode(SX.SECSFormat.A, 0, carrier.CarrierLoc, "Carrier Location[4]", new int[0]);
                }
            }
        }
        public void makeListS1F3EnhancedTransfer(ref SXTransaction transaction)
        {
            TransferWorkItem[] workList = this.LDispatcher.GetWorkList();
            if (workList == null || workList.Length == 0)
            {
                transaction.WriteNode(SX.SECSFormat.L, 0, "", "EnhancedTransfer[13]", new int[0]);
            }
            else
            {
                try
                {
                    transaction.WriteNode(SX.SECSFormat.L, workList.Length, "", "EnhancedTransfer[13]", new int[0]);
                    for (int i = 0; i < workList.Length; i++)
                    {
                        transaction.WriteNode(SX.SECSFormat.L, 3, "", "EnhancedTransferCommand[14]", new int[0]);
                        //指令传输状态
                        enumAimTransferState enumAimTransfer = this.ConvertMCSTrasferState(workList[i].TransferState);
                        transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)enumAimTransfer).ToString(), enumAimTransfer.ToString() + "-TransferState[32]", new int[0]);

                        transaction.WriteNode(SX.SECSFormat.L, 3, "", "CommandInfo[7]", new int[0]);
                        //指令ID
                        transaction.WriteNode(SX.SECSFormat.A, 0, workList[i].CommandID, "CommandID[6]", new int[0]);
                        //指令优先级
                        transaction.WriteNode(SX.SECSFormat.U2, 2, workList[i].Priority.ToString(), "Priority[21]", new int[0]);

                        transaction.WriteNode(SX.SECSFormat.A, 2, workList[i].CarrierType.ToString(), "CarrierType[21]", new int[0]);

                        transaction.WriteNode(SX.SECSFormat.L, 3, "", "TransferInfo[29]", new int[0]);
                        //指令绑定的物料ID
                        transaction.WriteNode(SX.SECSFormat.A, 0, workList[i].CarrierID, "CarrierID[3]", new int[0]);

                        //指令绑定的物料的当前位置
                        Carrier carrierUnsafe = Naming.GetCarrierManager().GetCarrierUnsafe(workList[i].CarrierID);
                        if (carrierUnsafe != null)
                        {
                            transaction.WriteNode(SX.SECSFormat.A, 0, carrierUnsafe.CarrierLoc, "Carrier Location[4]", new int[0]);
                        }
                        //指令传输目的地
                        transaction.WriteNode(SX.SECSFormat.A, 0, workList[i].Dest, "Dest[10]", new int[0]);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.loggerError("在方法[makeListS1F3EnhancedTransfer]报错", ex);
                }
            }
        }
        /// <summary>
        /// S1F4消息封装，获取Port口状态信息
        /// </summary>
        /// <param name="transaction"></param>
        public void makeListS1F3PortState(ref SXTransaction transaction)
        {

            List<ConveyorBuffer> conveyorBuffers = this.GetReportHostCV();
            int count = this.LifterPorts.Count + conveyorBuffers.Count;
            if (count == 0)
            {
                transaction.WriteNode(SX.SECSFormat.L, 0, "", "CurrentPortStates[13]", new int[0]);
            }
            else
            {
                transaction.WriteNode(SX.SECSFormat.L, count, "", "CurrentPortStates[13]", new int[0]);
                foreach (LifterPort current in this.LifterPorts.Values)
                {
                    transaction.WriteNode(SX.SECSFormat.L, 6, "", "PortInfo[20]", new int[0]);
                    //获取设备ID
                    transaction.WriteNode(SX.SECSFormat.A, 0, this.hostID, "LifterName[15]", new int[0]);
                    //获取Port口ID
                    transaction.WriteNode(SX.SECSFormat.A, 0, current.HostID, "PortIDi[18]", new int[0]);
                    enumPortStateForAim enumPortStateForAim = enumPortStateForAim.InService;
                    if (current.LifterPortState == enumRIDState.DOWN)
                    {
                        enumPortStateForAim = enumPortStateForAim.OutofService;
                    }
                    //获取Port口状态
                    transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)enumPortStateForAim).ToString(), enumPortStateForAim.ToString() + "-PortStatei[19]", new int[0]);
                    //获取Port口类型(OP/BP/LP/)
                    transaction.WriteNode(SX.SECSFormat.A, 0, current.LifterPortType.ToString(), "PortType[33]", new int[0]);

                    //获取Port IN/OUT模式
                    enumAIMLifertPortInOutType lifterPortInoutType = current.GetLifterPortInoutType();
                    transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)lifterPortInoutType).ToString(), lifterPortInoutType.ToString() + "-PortInOuttype[34]", new int[0]);

                    //获取Port 操作模式（AUTO/MANUAL）
                    transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)current.OperationModeForAIM).ToString(), current.OperationModeForAIM.ToString() + "-PortAccessMode[40]", new int[0]);
                }
                //同步CV数据状态
                foreach (ConveyorBuffer current in conveyorBuffers)
                {
                    LifterPort lifterPort = this.GetLifterPort(current.LifterPortID);
                    transaction.WriteNode(SX.SECSFormat.L, 6, "", "PortInfo[20]", new int[0]);
                    //获取设备ID
                    transaction.WriteNode(SX.SECSFormat.A, 0, this.hostID, "LifterName[15]", new int[0]);
                    //获取Port口ID
                    transaction.WriteNode(SX.SECSFormat.A, 0, current.HostID, "PortIDi[18]", new int[0]);
                    enumPortStateForAim enumPortStateForAim = enumPortStateForAim.InService;
                    if (lifterPort.LifterPortState == enumRIDState.DOWN)
                    {
                        enumPortStateForAim = enumPortStateForAim.OutofService;
                    }
                    //获取Port口状态
                    transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)enumPortStateForAim).ToString(), enumPortStateForAim.ToString() + "-PortStatei[19]", new int[0]);
                    //获取Port口类型(OP/BP/LP/)
                    transaction.WriteNode(SX.SECSFormat.A, 0, lifterPort.LifterPortType.ToString(), "PortType[33]", new int[0]);

                    //获取Port IN/OUT模式
                    enumAIMLifertPortInOutType lifterPortInoutType = lifterPort.GetLifterPortInoutType();
                    transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)lifterPortInoutType).ToString(), lifterPortInoutType.ToString() + "-PortInOuttype[34]", new int[0]);

                    //获取Port 操作模式（AUTO/MANUAL）
                    transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)lifterPort.OperationModeForAIM).ToString(), lifterPort.OperationModeForAIM.ToString() + "-PortAccessMode[40]", new int[0]);
                }
            }
        }
        /// <summary>
        /// S1F4消息封装，获取轿厢状态信息
        /// </summary>
        /// <param name="transaction"></param>
        public void makeListS1F3ShuttleState(ref SXTransaction transaction)
        {
            
            transaction.WriteNode(SX.SECSFormat.L, 1, "", "CurrentShuttleStates[9]", new int[0]);
            transaction.WriteNode(SX.SECSFormat.L, 4, "", "ShuttleInfo[24]", new int[0]);
            //获取设备ID
            transaction.WriteNode(SX.SECSFormat.A, 0, this.hostID, "LifterName[15]", new int[0]);
            //获取轿厢ID
            transaction.WriteNode(SX.SECSFormat.A, 0, this.shuttleMaster.HostID, "ShuttleID[25]", new int[0]);
            //获取轿厢当前位置
            foreach (LifterPort lifterPort in this.LifterPorts.Values)
            {
                if (this.ShuttleMaster.ShuttleFloor.Equals(lifterPort.Floor))
                {
                    transaction.WriteNode(SX.SECSFormat.A, 0, lifterPort.HostID, "LocationID[17]", new int[0]);
                    break;
                }
            }
            enumShuttleMasterStateForAim shuttleMasterStateForAim = enumShuttleMasterStateForAim.InService;
            if (this.shuttleMaster.ShuttleMasterStatus == enumRIDState.DOWN)
            {
                shuttleMasterStateForAim = enumShuttleMasterStateForAim.OutofService;
            }
            //获取轿厢状态
            transaction.WriteNode(SX.SECSFormat.U2, 2, ((int)shuttleMasterStateForAim).ToString(), shuttleMasterStateForAim.ToString() + "-ShuttleState[26]", new int[0]);
        }
        /// <summary>
        /// S1F4消息封装，获取alarm状态
        /// </summary>
        /// <param name="transaction"></param>
        public void makeListS1F3alarmState(ref SXTransaction transaction)
        {
            List<EcpAlarm> setedAlarmList = this.reportAlarms;
            //如果没有报警信息
            if (setedAlarmList == null || setedAlarmList.Count == 0)
            {
                transaction.WriteNode(SX.SECSFormat.L, 0, "", "AlarmSet[36]", new int[0]);
            }
            else
            {
                transaction.WriteNode(SX.SECSFormat.L, setedAlarmList.Count, "", "AlarmSet[36]", new int[0]);
                foreach (EcpAlarm current in setedAlarmList)
                {
                    transaction.WriteNode(SX.SECSFormat.L, 3, "", "AlarmSet[36]", new int[0]);
                    //获取设备ID
                    transaction.WriteNode(SX.SECSFormat.A, 0, this.hostID, "LifterName[15]", new int[0]);
                    //获取AlarmID
                    transaction.WriteNode(SX.SECSFormat.A, 0, current.ALID.ToString(), "Alarm ID[1]", new int[0]);
                    //获取Alarm内容
                    transaction.WriteNode(SX.SECSFormat.A, 0, current.ALTX, "Alarm Text", new int[0]);
                }
            }
        }
        private void ReplyS10F3(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            string sTerminalID = secsValue.GetValue("TERMINALID");
            string sTerminalMsg = secsValue.GetValue("TERMINALMESSAGE");
            secsValue.SetRequestValue("ACK", "0");
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
        }
        private void ReplyS2F31(string sxfx, SecsEventArgs e)
        {
            bool flag = true;
            SecsValue secsValue = e.SecsValue;
            string sDateTime = ((SEComData)secsValue.SecsData).DataItems[0].Value.ToString();
            if (sDateTime.Length < 16)
            {
                flag = false;
            }
            else
            {
                Util.SYSTEMTIME sYSTEMTIME = default(Util.SYSTEMTIME);
                try
                {
                    sYSTEMTIME.wYear = ushort.Parse(sDateTime.Substring(0, 4));
                    sYSTEMTIME.wMonth = ushort.Parse(sDateTime.Substring(4, 2));
                    sYSTEMTIME.wDay = ushort.Parse(sDateTime.Substring(6, 2));
                    sYSTEMTIME.wHour = ushort.Parse(sDateTime.Substring(8, 2));
                    sYSTEMTIME.wMinute = ushort.Parse(sDateTime.Substring(10, 2));
                    sYSTEMTIME.wSecond = ushort.Parse(sDateTime.Substring(12, 2));
                    sYSTEMTIME.wMilliseconds = ushort.Parse(sDateTime.Substring(14, 2));
                    Util.SetLocalTime(ref sYSTEMTIME);
                }
                catch (Exception ex)
                {
                    flag = false;
                    throw ex;
                }
            }
            e.SecsTransaction = S2F32.MakeTransactionSend(flag);
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
        }
        private void ReceiveS2F18(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            string sDateTime = secsValue.GetValue("DATETIME");
            Util.SYSTEMTIME setTime = default(Util.SYSTEMTIME);
            try
            {
                setTime.wYear = ushort.Parse(sDateTime.Substring(0, 4));
                setTime.wMonth = ushort.Parse(sDateTime.Substring(4, 2));
                setTime.wDay = ushort.Parse(sDateTime.Substring(6, 2));
                setTime.wHour = ushort.Parse(sDateTime.Substring(8, 2));
                setTime.wMinute = ushort.Parse(sDateTime.Substring(10, 2));
                setTime.wSecond = ushort.Parse(sDateTime.Substring(12, 2));
                setTime.wMilliseconds = ushort.Parse(sDateTime.Substring(14, 2));
                Util.SetLocalTime(ref setTime);
                this.SyncPCLTimeSet(setTime);
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("HOST时间同步报错", ex);
            }
        }
        private void ReplyS2F33(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            secsValue.SetRequestValue("ACK", "0");
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
        }
        private void ReplyS5F3(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            secsValue.SetRequestValue("ACK", "0");
            this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
        }
        private void ReplyS2F41(string sxfx, SecsEventArgs e)
        {
            S2F42.MakeTransactionSend(sxfx, e, this);
        }
        public void ReplyS2F41PORT_TYPE_CHANGE(ref SXTransaction sXTransaction,SEComData secsData)
        {
            string sCPName1 = secsData.DataItems[0][1][0][0].Value.ToString();
            string sCPValue1 = secsData.DataItems[0][1][0][1].Value.ToString();
            string sCPName2 = secsData.DataItems[0][1][1][0].Value.ToString();
            int sCPValue2 = int.Parse(secsData.DataItems[0][1][1][1].Value.ToString());

            //获取Host需要改变的状态值
            enumAIMLifertPortInOutType enumAIMLifertPortInOutType = (enumAIMLifertPortInOutType)sCPValue2;
            //获取Host需要改变哪个Port的状态
            LifterPort lifterPort = this.GetLifterPort(sCPValue1);
            //判断Host更改的Port口是否存在
            if (lifterPort != null)
            {
                //如果Port口方向可以改变
                if (lifterPort.IsPortDirChangeEnable)
                {
                    if (lifterPort.GetAimLifertPortInOutType() != enumAIMLifertPortInOutType)
                    {
                        sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CONFIRM).ToString(), "HACK", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                        if (enumAIMLifertPortInOutType == enumAIMLifertPortInOutType.BOTH)
                        {
                           lifterPort.PortModeReq(enumLifterPortDirection.BOTH);
                        }
                        if (enumAIMLifertPortInOutType == enumAIMLifertPortInOutType.OUTPUT)
                        {
                            lifterPort.PortModeReq(enumLifterPortDirection.OUT);
                        }
                        if (enumAIMLifertPortInOutType == enumAIMLifertPortInOutType.INPUT)
                        {
                            lifterPort.PortModeReq(enumLifterPortDirection.IN);
                        }
                    }
                    else
                    {
                        sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.AT_LEAST_ONE_PARAMETER_ISNT_VALID).ToString(), "HACK", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.L, 1, "", "", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.A, 0, sCPName1, "CPNAME", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.CPACK.CPVALUE_Incorrect_Value).ToString(), "CPACK", new int[0]);
                    }
                }
                else
                {
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.AT_LEAST_ONE_PARAMETER_ISNT_VALID).ToString(), "HACK", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 1, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.A, 0, sCPName1, "CPNAME", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.CPACK.CPVALUE_Incorrect_Value).ToString(), "CPACK", new int[0]);
                }
            }
            else
            {
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.AT_LEAST_ONE_PARAMETER_ISNT_VALID).ToString(), "HACK", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 1, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.A, 0, sCPName1, "CPNAME", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.CPACK.CPNAME_Does_Not_Exist).ToString(), "CPACK", new int[0]);
            }
        }
        public bool ReplyS2F41Pause(ref SXTransaction sXTransaction)
        {
            bool flag = true;
            if (this.sCStatemode == enumSCStateMode.SC_PAUSED || this.sCStatemode == enumSCStateMode.SC_PAUSING)
            {
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.ALREADY_REQUESTED).ToString(), "HACK", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                flag = false;
            }
            else
            {
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CONFIRM).ToString(), "HACK", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                flag = true;
            }
            return flag;
        }
        public void ReplyS2F41EntryValidation(string sxfx, SXTransaction sXTransaction, SecsValue secsValue)
        {
            SEComData secsData = (SEComData)secsValue.SecsData;
            string sCPName1 = secsData.DataItems[0][1][0][0].Value.ToString();
            string sCPValue1 = secsData.DataItems[0][1][0][1].Value.ToString();
            string sCPName2 = secsData.DataItems[0][1][1][0].Value.ToString();
            int sCPValue2 = int.Parse(secsData.DataItems[0][1][1][1].Value.ToString());

            //获取Host验证的结果
             int validationResult = sCPValue2;
            //获取Host需要验证哪个物料
            Carrier carrier = this.GetCarrierByCarrierID(sCPValue1);
            //判断Host验证的物料是否存在
            if (carrier != null)
            {
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CONFIRM).ToString(), "HACK", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                this.SecsDriver.ReplyMessage(sxfx, sXTransaction, secsValue);
                //后续逻辑操作(判断validationResult结果)
                //获取当前物料所在的Port口
                LifterPort lifterPort = this.GetLifterPort(carrier.CarrierLoc);
                if (lifterPort != null)
                {
                    if (validationResult == MsgConstant.ENTRYVALIDATION_SUCCESS_INT)
                    {
 /*                       //Port口为MGV模式，PC自动创建指令,触发OperationInitialAction事件
                        lifterPort.PCAutoCreateCommand();
                        //回复设备物料验证OK*/
                        lifterPort._O_BCRVERIFYOK = true;
                        LogHelper.loggerInfo("MCS验证OK,BCRVERIFYOK信号置ON");
                        Thread.Sleep(1500);
                        lifterPort._O_BCRVERIFYOK = false;
                        LogHelper.loggerInfo("MCS验证OK,BCRVERIFYOK信号置OFF");
                    }
                    else
                    {
                        //验证失败,触发报警
                        //回复设备物料验证NG
                        lifterPort._O_BCRVERIFYNG = true;
                        LogHelper.loggerInfo("MCS验证NG,BCRVERIFYNG信号置ON");
                        Thread.Sleep(1500);
                        lifterPort._O_BCRVERIFYNG = false;
                        LogHelper.loggerInfo("MCS验证NG,BCRVERIFYNG信号置OFF");
                    }
                }
                else
                {
                    //弹窗提醒，或记录log日志（MGVPort口EntryValidation事件验证的物料Location不正确）
                    LogHelper.loggerInfo("MGVPort口EntryValidation事件验证的物料Location不正确");
                }
            }
            else
            {
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.AT_LEAST_ONE_PARAMETER_ISNT_VALID).ToString(), "HACK", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 1, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.A, 0, sCPName1, "CPNAME", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.CPACK.CPNAME_Does_Not_Exist).ToString(), "CPACK", new int[0]);
                this.SecsDriver.ReplyMessage(sxfx, sXTransaction, secsValue);
            }
        }
        public void ReplyS2F41Install(string sxfx, SXTransaction sXTransaction, SecsValue secsValue)
        {
            try
            {
                //解析MCS数据
                SEComData secsData = (SEComData)secsValue.SecsData;
                string sCPName1 = secsData.DataItems[0][1][0][0].Value.ToString();
                string materialID = secsData.DataItems[0][1][0][1].Value.ToString();//MCS下发的物料ID
                string sCPName2 = secsData.DataItems[0][1][1][0].Value.ToString();
                string lifterID = secsData.DataItems[0][1][1][1].Value.ToString();//MCS下发的物料ID，对应的Port口

                Carrier carrier = this.GetCarrierByCarrierID(materialID);
                LifterPort lifterPort = this.GetLifterPort(lifterID);

                //如果Port口不存在
                if (lifterPort == null)
                {
                    LogHelper.loggerInfo(string.Format("MCS下达的物料ID[{0}],对应的Port[1]不存在！！", materialID, lifterID));
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.OBJECT_DOSE_NOT_EXIST).ToString(), "HACK", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 1, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.A, 0, sCPName2, "CPNAME", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.CPACK.CPVALUE_Incorrect_Value).ToString(), "CPACK", new int[0]);
                    this.SecsDriver.ReplyMessage(sxfx, sXTransaction, secsValue);
                }
                //如果物料在设备中已经存在
                else if (carrier != null)
                {
                    LogHelper.loggerInfo(string.Format("MCS下达的物料ID[{0}]已存在！！", materialID));
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.OBJECT_DOSE_NOT_EXIST).ToString(), "HACK", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 1, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.A, 0, sCPName1, "CPNAME", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.CPACK.CPVALUE_Incorrect_Value).ToString(), "CPACK", new int[0]);
                    this.SecsDriver.ReplyMessage(sxfx, sXTransaction, secsValue);
                }
                else
                {
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CONFIRM).ToString(), "HACK", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                    this.SecsDriver.ReplyMessage(sxfx, sXTransaction, secsValue);

                    //判断BCR是否禁用，如果禁用BCR，则使用MCS给的物料ID
                    if (lifterPort.BCREnableMode == enumBCREnableMode.DISABLE)
                    {
                        lifterPort.I_BUFFERMATERIALID = materialID;
                        LogHelper.loggerInfo(string.Format("在BCR禁用模式下，将MCS给的物料ID[{0}],下达给Port[{1}]口", materialID, lifterID));

                        //创建物料对象
                        lifterPort.CarrierId = materialID;
                        this.InstallMaterial(materialID, lifterID, "", CarrierState.INSTALLED, CarrierType.CA_TRAY, enumBCREnableMode.DISABLE.ToString(), Carrier.MaterialCreateTypeConstants.AUTO);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在ReplyS2F41Install方法中报错",ex);
            }
        }
        public bool ReplyS2F41Resume(ref SXTransaction sXTransaction)
        {
            bool flag = true;
            LifterSEM lifterSEM = (LifterSEM)Naming.GetDeviceManager().GetDevice();

            if (lifterSEM.hostControlState == enumHostControlState.SC_OFFLINE_HOST)
            {
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CURENTLY_NOT_ABLE_TO_EXECUTED).ToString(), "HACK", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                flag = false;
            }
            else
            {
                sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CONFIRM).ToString(), "HACK", new int[0]);
                sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                flag = true;
            }
            return flag;
        }
        private void ReplyS2F49Transfer(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            SEComData secsData = (SEComData)secsValue.SecsData;
            SXTransaction sXTransaction = new SXTransaction();
            string strDesc = "";

            string strDataID = secsData.DataItems[0][0].Value.ToString();
            string strObjectSpecific = secsData.DataItems[0][1].Value.ToString();
            string strRemoteCommand = secsData.DataItems[0][2].Value.ToString();
            string strCommandID = secsData.DataItems[0][3][0][1][0][1].Value.ToString();
            string strPriority = secsData.DataItems[0][3][0][1][1][1].Value.ToString();
            string carrierType = secsData.DataItems[0][3][0][1][2][1].Value.ToString();
            string cpnameCarrierID = secsData.DataItems[0][3][1][1][0][0].Value.ToString();
            string strCarrierID = secsData.DataItems[0][3][1][1][0][1].Value.ToString();
            string cpnameSource = secsData.DataItems[0][3][1][1][1][0].Value.ToString();
            string strSource = secsData.DataItems[0][3][1][1][1][1].Value.ToString();
            string cpnameDestination = secsData.DataItems[0][3][1][1][2][0].Value.ToString();
            string strDestination = secsData.DataItems[0][3][1][1][2][1].Value.ToString();
            secsValue.AddValue("DATAID", strDataID);
            secsValue.AddValue("OBJECTSPECIFIC", strObjectSpecific);
            secsValue.AddValue("REMOTECOMMAND", strRemoteCommand);
            secsValue.AddValue("COMMANDID", strCommandID);
            secsValue.AddValue("PRIORITY", strPriority);
            secsValue.AddValue("CARRIERID", strCarrierID);
            secsValue.AddValue("SOURCE", strSource);
            secsValue.AddValue("DESTINATION", strDestination);
            secsValue.AddValue("CARRIERTYPE", carrierType);

            //check host下达的指令是否正确
            enumNewTrasferCmdAvailable checkResult = this.CheckNewTrasferCmdAvailable(strCarrierID, strSource, strDestination, out strDesc);

            S2F50.MakeTransactionSend(ref sXTransaction);

            CarrierManager carrierManager = Naming.GetCarrierManager();
            Carrier carrier = null;

            switch (checkResult)
            {
                case enumNewTrasferCmdAvailable.NONE:
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.OBJECT_DOSE_NOT_EXIST).ToString(), "HCACK", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.A, 1, strRemoteCommand, "CPNAME", new int[0]);
                    sXTransaction.WriteNode(SX.SECSFormat.U1, 1, ((int)MsgACK.CEPACK.CPNAME_Not_Valid).ToString(), "CPEACK", new int[0]);
                    this.secsDriver.ReplyMessage(sxfx, sXTransaction, e.SecsValue);
                    break;
                case enumNewTrasferCmdAvailable.AVAIL:
                    {
                        carrier = carrierManager.GetCarrier(strCarrierID);
                        TransferWorkItem transferWorkItem = new TransferWorkItem
                        {
                            CommandID = strCommandID,
                            CarrierID = carrier.CarrierId,
                            Priority = Convert.ToInt32(strPriority),
                            Source = strSource,
                            Dest = strDestination,
                            CarrierLoc = carrier.CarrierLoc
                        };
                        if (MsgConstant.MATERIALTYPE_BOX.Equals(carrierType))
                        {
                            transferWorkItem.CarrierType = CarrierType.CA_BOX;
                        }
                        else if (MsgConstant.MATERIALTYPE_TRAY.Equals(carrierType))
                        {
                            transferWorkItem.CarrierType = CarrierType.CA_TRAY;
                        }
                        else if (MsgConstant.MATERIALTYPE_CST.Equals(carrierType))
                        {
                            transferWorkItem.CarrierType = CarrierType.CA_CST;
                        }
                        else
                        {
                            transferWorkItem.CarrierType = CarrierType.CA_ERROR;
                        }
                        sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CONFIRM).ToString(), "HCACK", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                        e.SecsTransaction = sXTransaction;
                        this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);
                        carrier.CommandID = transferWorkItem.CommandID;
                        TransferWorkItem transferWork = this.LDispatcher.GetJobByCarrierID(transferWorkItem.CarrierID);
                        if (transferWork != null)
                        {
                            this.LDispatcher.RemoveWork(transferWork);
                            LogHelper.loggerInfo($"MCS给物料[{carrier.CarrierId}]下发的指令信息已经存在");

                        }
                        this.LDispatcher.AddNewTransferQueue(transferWorkItem);
                        carrier.Update();
                        MaterialInfoControl.materialInfoControl.UpdateDelegate();
                        break;
                    }
                case enumNewTrasferCmdAvailable.NOT_AVAIL_DEST_DIRECTION_WRONG://目标Port口的方向不一致（Port的方向为In）
                    {
                        carrier = carrierManager.GetCarrier(strCarrierID);
                        sXTransaction.WriteNode(SX.SECSFormat.L, 2, "", "", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.B, 1, ((int)MsgACK.HCACK.CONFIRM).ToString(), "HCACK", new int[0]);
                        sXTransaction.WriteNode(SX.SECSFormat.L, 0, "", "", new int[0]);
                        e.SecsTransaction = sXTransaction;
                        this.secsDriver.ReplyMessage(sxfx, e.SecsTransaction, e.SecsValue);

                        //上报MCS TransferComplete事件，resultCode = 6（Dest PortInOutTypemismatch）
                        TransferWorkItem transferWorkItem = new TransferWorkItem();
                        transferWorkItem.CommandID = strCommandID;
                        transferWorkItem.CarrierID = carrier.CarrierId;
                        transferWorkItem.Source = carrier.CarrierLoc;
                        transferWorkItem.Dest = carrier.CarrierLoc;
                        transferWorkItem.CarrierLoc = carrier.CarrierLoc;
                        transferWorkItem.ResultCode = enumTransferResult.DEST_PORT_INOUTTYPE_MISTMATCH;
                        //上报MCS transferCompleted状态
                        this.SecsDriver.SendMessage("S6F11", "207", transferWorkItem);

                        //目标口的Port方向不匹配,触发超时自动生成指令逻辑，上报MCS
                        //this.CreateCarrierCommandByTimeOut();

                        break;
                    }
            }
        }
        private void ReplyS2F49(string sxfx, SecsEventArgs e)
        {
            SecsValue secsValue = e.SecsValue;
            this.ReplyS2F49Transfer(sxfx, e);
            /*            string strCommand = secsValue.GetValue("TRANSFER");
                        if (strCommand != null)
                        {
                            if (strCommand == "TRANSFERUPDATE")
                            {
                                this.ReplyS2F49TransferUpdate(sxfx, e);
                            }
                            else if (strCommand == "TRANSFER")
                            {

                            }
                        }*/
        }
        public string GetTransferStateAIMValue(TransferWorkItem workItem)
        {
            string result;
            switch (workItem.TransferState)
            {
                case enumTransferState.CREATE:
                    result = "1";
                    break;
                case enumTransferState.READY:
                    result = "1";
                    break;
                case enumTransferState.NOTREADY:
                    result = "1";
                    break;
                case enumTransferState.TRANSFERRING:
                    result = "2";
                    break;
                case enumTransferState.PAUSED:
                    result = "3";
                    break;
                case enumTransferState.CANCELING:
                    result = "4";
                    break;
                case enumTransferState.ABORTING:
                    result = "5";
                    break;
                case enumTransferState.COMPLETED:
                    result = "6";
                    break;
                default:
                    result = "0";
                    break;
            }
            return result;
        }
        /// <summary>
        /// 获取Vid值,返回的字典，键为字段名
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, string> getVidValueForHost()
        {
            Dictionary<string, string> VidValue = new Dictionary<string, string>();
            VidValue.Add("LifterName", this.HostID);
            VidValue.Add("SCState", ((int)this.SCStatemode).ToString());
            return VidValue;
        }
        #region add by yangshl 2023/9/22 LifterSEM方法
        /// <summary>
        /// add by yangshl 2023/9/22
        /// 根据楼层获取port集合
        /// </summary>
        /// <param name="floor"></param>
        /// <returns></returns>
        public List<LifterPort> GetLifterPortByFloor(int floor)
        {
            List<LifterPort> lifterPorts = new List<LifterPort>();
            foreach (LifterPort lifterPort in this.LifterPorts.Values)
            {
                if (lifterPort.Floor == floor)
                {
                    lifterPorts.Add(lifterPort);
                }
            }
            return lifterPorts;
        }

        /// <summary>
        /// 清除无效的物料信息
        /// ADD BY YSL 2024.1.18
        /// </summary>
        public void ClearInvalidMaterial()
        {
            try
            {
                List<string> invalidMaterials = new List<string>();
                foreach (Carrier carrier in Naming.GetCarrierManager().carriers.Values)
                {
                    LocationUnit locationUnit = GetLocationUnit(carrier.CarrierLoc);
                    if (locationUnit is LifterPort)
                    {
                        LifterPort lifterPort = (LifterPort)locationUnit;
                        if (!lifterPort.CarrierPresence[1])
                        {
                            carrier.CompleteResult = Carrier.MaterialCompleteTypeConstants.RESULT_NG_CANCEL;
                            invalidMaterials.Add(carrier.CarrierId);
                        }
                    }
                    else if (locationUnit is ConveyorBuffer)
                    {
                        ConveyorBuffer conveyorBuffer = (ConveyorBuffer)locationUnit;
                        if (!conveyorBuffer.CstPresence)
                        {
                            carrier.CompleteResult = Carrier.MaterialCompleteTypeConstants.RESULT_NG_CANCEL;
                            invalidMaterials.Add(carrier.CarrierId);
                        }
                    }
                    else if (locationUnit is Vehicle)
                    {
                        Vehicle vehicle = (Vehicle)locationUnit;
                        if (!vehicle.IsCSTPresenceOn)
                        {
                            carrier.CompleteResult = Carrier.MaterialCompleteTypeConstants.RESULT_NG_CANCEL;
                            invalidMaterials.Add(carrier.CarrierId);
                        }
                    }
                }
                if (invalidMaterials.Count > 0)
                {
                    foreach (string invalidMaterial in invalidMaterials)
                    {
                        Naming.GetCarrierManager().DeleteCarrier(invalidMaterial);
                        MaterialInfoControl.materialInfoControl.UpdateDelegate();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取需要上报MCS状态及方向的CV
        /// ADD BY YSL 2024.1.18
        /// </summary>
        /// <returns></returns>
        public List<ConveyorBuffer> GetReportHostCV()
        {
            List<ConveyorBuffer> conveyorBuffers = new List<ConveyorBuffer>();
            foreach (ConveyorBuffer conveyorBuffer in this.ConveyorBuffers.Values)
            {
                if (conveyorBuffer.IsReportHost)
                {
                    conveyorBuffers.Add(conveyorBuffer);
                }
            }
            return conveyorBuffers;
        }
        public void InsertUserOperation(string userName, string mssage)
        {
            UserOperationDao userOperationDao = new UserOperationDao();
            userOperationDao.UserName = userName;
            userOperationDao.EventDesc = mssage;
            userOperationDao.EventTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            UserManager.InsertUserOperation(userOperationDao);
        } 
        public void InitEnableMode()
        {
            foreach (LifterPort lifterPort in this.LifterPorts.Values)
            {
                if (lifterPort.UseChange)
                {
                    lifterPort.O_ENABLEMODECHANGE = true;
                }
                else
                {
                    lifterPort.O_ENABLEMODECHANGE = false;
                }
            }
        }
        public List<string> PortIDToHostID()
        {
            List<string> portIDs = new List<string>();
            foreach (LifterPort port in this.LifterPorts.Values)
            {
                portIDs.Add(port.HostID);
            }
            return portIDs;
        }
        #endregion
    }
}
